Reputation: 442
I have been trying to get this to work for a while and I have searched high and low for answers (including here). But I can't figure it out.
So here the code (a bit minimized):
public class Event<T> {
public MessageType msgType;
public int layer;
public int gameObjectId;
public String name;
public float value;
public int senderId;
public T ext;
public Event(Class<T> classType) {
if(classType != null) {
try {
ext = classType.newInstance(); //this is the failing line
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
msgType = MessageType.NONE;
layer = TypeHandler.lAll;
gameObjectId = -1;
name = null;
value = -1;
}
}
public class DataExtension {
public float[] values;
public String[] string;
public Object[] objects;
public boolean[] boolens;
}
This is the problem:
Event<DataExtension> mSelectionEvent;
mSelectionEvent = new Event<DataExtension>(DataExtension.class, MessageType.SELECTED);
This give me the following exception:
java.lang.InstantiationException: se.plainentertainment.bagl.v2.core.Event$DataExtension
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at se.plainentertainment.bagl.v2.core.Event.<init>(Event.java:85)
at se.plainentertainment.bagl.v2.core.SelectionHandler.<init>(SelectionHandler.java:46)...
So, the class that I'm trying to instantiate should meet all the requirements, right? It has a default constructor and it's not abstract in any way. Why do I get this error?
Thanks in advance!
Upvotes: 0
Views: 608
Reputation: 8586
Event$DataExtension
This is an inner class. Is it static? I'm going to go with a hunch and say no. Which means it contains a reference to the containing Event (implicitly), which means you likely can't instantiate it via newInstance.
Try setting it to be a static inner class, or move it out of the class it if it doesn't need to be tied to the event object.
Upvotes: 1