Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null pointer exception when working with generics in java

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.

like image 562
Pablo Avatar asked Dec 13 '22 06:12

Pablo


1 Answers

You're calling type.getClass() but at that point type is guaranteed to be null. No other code will have had a chance to set it yet, so how did you expect it to work? You say you're confused about why it's null - but you haven't shown anything which would make it non-null.

I suspect you want something like:

public abstract class ExcelReader<T>{
     protected final Class<T> type;
     protected GenericResolver resolver;

     public ExcelReader(Class<T> type){
        this.type = type;
        resolver = ResolverFactory.createResolver(type); 
     }
}

You'd want to introduce the same sort of parameter on the subclasses too.

like image 77
Jon Skeet Avatar answered Feb 08 '23 22:02

Jon Skeet