Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting T.class despite Java's type-erasure

I'm trying to bind an interface to its implementation as read from a configuration file so that I can feed it to my IoC container. Here's roughly what I'm trying to do:

public class PropertyImplementationBinder<T> {
    // ...
    public Class getInterfaceClass() {
        return T.class; // OR Class<T>, note T is not newable
    }
    public Class getImplementationClass() {
        return /* read config file to get implementation class */;
    }
}

Is it somehow possible to get T.class?

like image 801
Kaleb Pederson Avatar asked Feb 09 '10 00:02

Kaleb Pederson


People also ask

Which class is used during the erasure process by the compiler?

Class Type Erasure. At the class level, the compiler discards the type parameters on the class and replaces them with its first bound, or Object if the type parameter is unbound.

How Generics works in Java What is type erasure?

Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to: Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded.

Does C# use type erasure?

C# does not have type erasure. C# has actual generic types deeply baked into the runtime.

What is the T class in Java?

< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.


1 Answers

You need to explicitly pass the class into the constructor (and store it yourself).

private final Class<T> clazz;

PropertyImplementationBinder(Class<T> clazz){
    this.clazz = clazz;
}

public Class<T> getInterfaceClass() {
    return clazz;
}
like image 131
Thilo Avatar answered Sep 21 '22 15:09

Thilo