Reputation: 97
I have a java class Jist
that has two fields, public final Object type
and public Object[] content
. In the constructor for Jist
I want to take in an Object
and get its type, then initialize content
with some number of empty slots of that type. This is one of the several solutions that I have tried, and the error that I am currently receiving is in the actual initialization of the array:
public class Jist{
public final Object type;
public Object[] content;
public Jist(Object type){
this.type = type.getClass();
class myType extends Jist{
Class c = super.type.getClass();
public Class getType(){
return c;
}
};
content = new myType.getType()[4];
}
}
Upvotes: 0
Views: 761
Reputation: 56
Yes, you can create new array instance using type Class.
Class<?> myTypeClass = myType.getType();
int arraySize = 10;
Object array = Array.newInstance(myTypeClass, arraySize);
https://docs.oracle.com/javase/tutorial/reflect/special/arrayInstance.html
Upvotes: 0
Reputation: 201429
Make Jist
generic on some type T
. Pass the Class<T>
in the constructor. Use Array.newInstance(Class<?>, int)
like
public class Jist<T> {
public final Class<T> type;
public T[] content;
public Jist(Class<T> cls) {
this.type = cls;
content = (T[]) Array.newInstance(type, 4);
}
}
Upvotes: 1