since I have not been using generics for some time, I’m quite confused at this example.
I have the following base abstract class:
public abstract class ExcelReader<T>{
protected T type;
protected GenericResolver resolver;
public ExcelReader(){
super();
resolver=ResolverFactory.createResolver(type.getClass());
}
}
now my subclass is the following:
public class POIReader<T> extends ExcelReader<T>{
}
//...Implementation of methods ommited for brevity
Now in my service I’m creating a new object in the following way:
ExcelReader<MessageDTO> reader=new POIReader<MessageDTO>();
However, when the ExcelReader constructor is called the type attribute has null, and in consecuence throwing a NullPointer exception when creating the resolver.
I think you can get the idea of what I’m trying to do with the code fragments above, and I have seen examples using an attribute field to save the Parametized Class type.
However I’m quite confused in why I’m getting null in the type attribute, and how could I avoid it.
Thanks a lot.
I don’t think you are trying to use the generics for the thing they were intended to use. Generics are a kind of “syntactic sugar” usable in compile-time only as an additional level of code validation. What you seem to want to achieve – correct me if I am wrong – is to provide the generic type to your POIReader class and then be able (in runtime) to access this type’s class object. Is this correct?
The way you could use the generics in your example – but I am not sure this will be what you want to achieve – is for something like this:
and then:
This way, thanks to using generics the compiler will not allow you to pass anything that is not assignable to a
MessageDTOclass as the argument toPOIReader‘s constructor – but you still must assign something to that value field in order to be able to call thegetClass()method. This is because, due to type erasure of generics (an unfortunate backwards-compatibility thing), generics you provide are not available in runtime, only in compile-time.