[英]Is there a way to make an array of a user-defined class type in java?
I have a java class Jist
that has two fields, public final Object type
and public Object[] content
.我有一个 Java 类
Jist
,它有两个字段, public final Object type
和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.在
Jist
的构造函数中,我想接收一个Object
并获取它的类型,然后用一些该类型的空槽初始化content
。 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];
}
} }
Make Jist
generic on some type T
.在某些类型
T
上使Jist
泛型。 Pass the Class<T>
in the constructor.在构造函数中传递
Class<T>
。 Use Array.newInstance(Class<?>, int)
like使用
Array.newInstance(Class<?>, int)
像
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);
}
}
Yes, you can create new array instance using type Class.是的,您可以使用 Class 类型创建新的数组实例。
Class<?> myTypeClass = myType.getType();
int arraySize = 10;
Object array = Array.newInstance(myTypeClass, arraySize);
https://docs.oracle.com/javase/tutorial/reflect/special/arrayInstance.html https://docs.oracle.com/javase/tutorial/reflect/special/arrayInstance.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.