Understanding Mockito's Type Inference Trick in the mock() Method

Recently, I nearly misinterpreted code authored by a team member contrary to its intended purpose. The implementation initially appeared counterintuitive, prompting thorough reinvestigation documented herein. The team member’s code utilized generics for creating a method applicable to API invocations in a versatile manner. The explanation referenced employing an identical technique to Mockito library’s mock() method, warranting examination. Type Inference in Mockito’s mock() (Version: mockito-core 4.9 or higher, included in spring-boot-starter-test from 3.1 onwards) ...

January 19, 2025 · 729 words · Mihyang Gu

Generic Type Variance: Invariance, Covariance, and Contravariance

While working with Spring Batch, I encountered ItemWriter’s method void write(List<? extends T> var1) and pondered the rationale for such generic type specification. I have finally undertaken comprehensive investigation. Contravariance concepts proved conceptually challenging, requiring several hours to achieve comprehension. However, upon understanding, the underlying principles appear remarkably straightforward. This exposition attempts maximal clarity. Generic Terminology Initially, I had forgotten even the appropriate search terminology, necessitating terminological review. These terms follow Effective Java conventions. ...

November 7, 2021 · 796 words · Mihyang Gu

Java Interface vs Abstract Class: When to Use What

While “the distinction between interfaces and abstract classes” constitutes a common inquiry, investigation beyond superficial differences reveals remarkably diverse perspectives. Java 8’s introduction of default methods in interfaces substantially diminished the distinctions between the two constructs. This exposition examines in detail when each proves most appropriate. Fundamental Characteristics Let us first examine the basic characteristics. Interface May contain constants (static final) and abstract methods 1 2 3 4 interface Barkable { public static final int BLABLA_CONSTANT = 1; public abstract void bark(); } Java 8 introduced default methods (permitting complete implementation) ...

October 24, 2021 · 890 words · Mihyang Gu