andrew
andrew

Reputation: 11

NullPointerException creating generic type instance

Here is my Class

public class ManagerForm<M extends Stuff>{
private Class<M>clazz;
private M manager;

public void setWorker(M manager){
this.manager=manager;
}
public M getWorker(){
return this.manager;
}

private final Class<M> getGenericClass() {
        Class<M> persistentClass = null;
        Type genericType = getClass().getGenericSuperclass();
        if (genericType instanceof ParameterizedType) {
            ParameterizedType pType = ((ParameterizedType) genericType);
            // obtaining first generic type class
            persistentClass = (Class<M>) pType.getActualTypeArguments()[0];
        }
        return persistentClass;
    }

public ManagerForm(){
this.clazz=getGenericClass();
this.manager=this.clazz.newInstance();
}
}

In default constructor in line this.user=this.clazz.newInstance(); I have NullPointer exception Request processing failed; nested exception is java.lang.NullPointerException

Could anybody help me. What is going on? Why clazz creates null instance? Where is my mistake?

Thanks in advance.

UPD

genericType belongs to Object type and is not instance of ParameterizedType. That's why function getGenericType returns null. Why?

When I use Type genericType = getClass() instead of Type genericType = getClass().getGenericSuperclass(); I can get ManagerForm type. But ManagerForm doest belong to instance of ParameterizedType too?

Could anybody clear the situation?

Upvotes: 0

Views: 794

Answers (2)

Petar Ivanov
Petar Ivanov

Reputation: 93050

In your getGenericClass function:

genericType instanceof ParameterizedType

probably returns false, so persistentClass is null.

Upvotes: 4

Brett Walker
Brett Walker

Reputation: 3586

I would say that the if block within getGenericClass is not being executed. So the initial value of persistentClass is being returned. Having not run the code I could be wrong.

Upvotes: 0

Related Questions