惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Full Disclosure
WordPress大学
WordPress大学
小众软件
小众软件
Cloudbric
Cloudbric
AWS News Blog
AWS News Blog
腾讯CDC
量子位
人人都是产品经理
人人都是产品经理
大猫的无限游戏
大猫的无限游戏
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
Vulnerabilities – Threatpost
Scott Helme
Scott Helme
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Hacker News
The Hacker News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
IT之家
IT之家
Jina AI
Jina AI
Attack and Defense Labs
Attack and Defense Labs
S
SegmentFault 最新的问题
Simon Willison's Weblog
Simon Willison's Weblog
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
T
Tailwind CSS Blog
Last Week in AI
Last Week in AI
博客园 - 【当耐特】
Google Online Security Blog
Google Online Security Blog
美团技术团队
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
Visual Studio Blog
罗磊的独立博客
L
LINUX DO - 最新话题
博客园 - Franky
博客园 - 叶小钗
Apple Machine Learning Research
Apple Machine Learning Research
The Last Watchdog
The Last Watchdog
J
Java Code Geeks
AI
AI
C
Cisco Blogs
酷 壳 – CoolShell
酷 壳 – CoolShell
C
Cyber Attacks, Cyber Crime and Cyber Security
Cisco Talos Blog
Cisco Talos Blog
博客园 - 三生石上(FineUI控件)
雷峰网
雷峰网
Help Net Security
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
云风的 BLOG
云风的 BLOG
I
Intezer
S
Securelist

Maciej Walkowiak - Java & Spring

Blog Generating HTTP clients in Spring Boot application from OpenAPI spec PostgreSQL and UUID as primary key Dynamic Projections with Spring Data JPA Container logs with Spring Boot and Testcontainers Faster integration tests with reusable Testcontainers and Flyway Running one-time jobs with Quartz and Spring Boot The best way to use Testcontainers with Spring Boot Spring Boot & Flyway - clear database between integration tests What's new in Spring? Activate Maven Profile by Operating System Spring Boot with Thymeleaf and Tailwind CSS - Complete Guide How to publish a Java library to Maven Central - Complete Guide Docker Compose - waiting until containers are ready Single file Java applications with JBang Beautiful bash scripts with Gum Running Java on CRaC How to log PostgreSQL queries with Testcontainers Spring Boot 3.0 & GraalVM Native Image - not a free lunch Creating Spring Cloud Function projects with AWS SAM Loading classpath resources to String with a custom JUnit extension Creating Project Templates with Cookiecutter Auto-Registering JUnit 5 extensions Spring Boot component scanning without annotations Listing Maven dependencies in Spring Boot Actuator Info endpoint Spring Cloud AWS 2.3 RC2 Released How I built vlad-cli - command line interface to Vlad Mihalcea The State of Java Relational Persistence On Choosing a Tech Stack
Reified Generics in Java?
2023-10-23 · via Maciej Walkowiak - Java & Spring
Published on
  • Java

A common pattern in Java, whenever there is a need retrieve data from a database or deserialize JSON is to pass the target object class as a parameter.

A good example is Jackson's ObjectMapper#readValue method with following signature:

java

public <T> T readValue(String content, Class<T> valueType) {
    ...
}

Passing class as a parameter looks repetitive. Since <T> defines the type, why do we need to pass Class<T>? Why it can't be simplified to:

java

public <T> T readValue(String content) {
    ...
}

And most importantly, how is Mockito able to find out the type of mock in such code?

java

Book book = mock();
Person person = mock();

What kind of sorcery is that?


Type Erasure ​

Reified Generics is a type system that makes generics type information available in runtime. Java does not support reification for many reasons explained in depth in essay Background: How We Got the Generics We Have written by Brian Goetz. One of them is backward compatibility. Generics were introduced in Java 1.5 on the 30th of September 2005 - almost 9 years after Java 1.0 release. Brian writes:

Migration compatibility. There was no known translation scheme at the time that would have allowed a migration to reified generics to be source- and binary-compatible, creating flag days and invalidating developer’s considerable investment in their existing code.

Lack of reified generics, or type erasure, in practice means that List<String> list = new ArrayList<String>() in runtime is an equivalent of List list = new ArrayList() - generics information is lost and the information about the type must be passed with extra Class parameter. Such pattern is heavily used not only in Jackson but also Spring's JdbcTemplate and pretty much every library that deserializes or converts data into Java objects.

java

class JdbcTemplate {
    // ...
    <T> T queryForObject(String sql, Class<T> requiredType) {
        // ...
    }
}

Array type hack ​

Back to Mockito example. In the past, to create mocks we had to pass Class to the Mockito#mock method - similar to previous Jackson and JdbcTemplate examples:

java

Book book = mock(Book.class);
Person person = mock(Person.class);

This has changed in Mockito 4.9.0 released in November 2022 where the extra Class parameter is not needed any longer:

java

Book book = mock();
Person person = mock();

Considering what we've just discussed type erasure and lack of reified generics - this looks like magic. How can Mockito know the type if generics type information is erased?

Lets take a look at the mock method signature

java

<T> T mock(T... reified)

It takes an array reified of type T. When mock is created with mock(), parameter value is turned into an empty array. Generics type gets erased but arrays type are reified - type of array is available in runtime and can be retrieved in following way:

java

static <T> Class<T> getClassOf(T[] array) {
    return (Class<T>) array.getClass().getComponentType();
}

It is a hack, it makes mock method API less obvious, but at the same time it is brilliant and very convenient for users.

INFO

This hack was discovered and described by Tagir Valeev and mock() method in Mockito was directly inspired by his tweet.

While I don't think such hack should become a norm, for certain use cases it may be worth it! Perhaps one day we will get reified generics in Java and such hacks won't be even discussed.

Let's stay in touch and follow me on Twitter: @maciejwalkowiak

Subscribe to RSS feed