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
?
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.
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.
C# does not have type erasure. C# has actual generic types deeply baked into the runtime.
< 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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With