How does guice's TypeLiteral work?

前端 未结 2 1435
走了就别回头了
走了就别回头了 2021-01-30 22:29

How does Guice\'s TypeLiteral overcome the Java generic types erasure procedure?

It works wonders but how is this accomplished?

2条回答
  •  不知归路
    2021-01-30 23:16

    By a combination of anonymous types, subclassing and the fact that Java does not completely erase ALL generic declarations.

    If you look closely the TypeLiteral has a protected constructor so you use an additional {} when constructing a new one which creates an anonymous subclass of TypeLiteral.

    In Java generic declarations are preserved on Class and Method declarations, so if I write this.

    public abstract class Class1
    {
    }
    
    public class Class2 extends Class1
    {
    }
    

    I can actually write code in Class1 that can figure out that its own generic type is Integer if Class2 was the subclass.

    Check out the java.lang.Class API for the appropriate methods (they have Generic in the name).

提交回复
热议问题