[英]Java Instantiate Generic Type
I have a class that takes in two parameterized types and I want to have a method that returns a new instance of one of the types. 我有一个接受两个参数化类型的类,并且我想有一个返回一个类型的新实例的方法。 This is the class:
这是课程:
public class StateMachine<S extends State, E extends StateObject> {
// State
protected ArrayMap<S, E> states;
protected E currentState;
protected Entity entity;
// Bits
private Builder builder = new Builder();
private int bitOffset;
private boolean firstState = false;
public StateMachine(Entity entity) {
this.entity = entity;
states = new ArrayMap<S, E>();
}
public E createState(S key) {
// State identifiers must also be taggable
assert (key instanceof Tag);
if (!firstState) {
firstState = true;
bitOffset = key.numStates();
}
E state = (E) new StateObject(entity);
state.bitOffset = bitOffset;
state.bits.set(((Tag) key).getIndex());
states.put(key, state);
return state;
}
// Remainder omitted....
}
As you can see, I want to create a state and return its value based on the parameterized type. 如您所见,我想创建一个状态并根据参数化类型返回其值。 Currently, I have an
EntityState
class that extends StateObject
and have an EntityStateMachine
that extends StateMachine
with the parameters <StateIdentifier, EntityState>
. 目前,我有一个
EntityState
延伸类StateObject
并具有EntityStateMachine
延伸StateMachine
与参数<StateIdentifier, EntityState>
However, when I call createState
from the EntityStateMachine
, the returned value is not an EntityState
but rather a StateObject
. 但是,当我从
EntityStateMachine
调用createState
时,返回的值不是EntityState
而是StateObject
。
How can I ensure that the returned value is casted to proper parameterized type? 如何确保将返回值转换为正确的参数化类型?
Java pattern to deal with this is to store Class<E>
, and use its newInstance
method, as follows: 处理此问题的Java模式是存储
Class<E>
,并使用其newInstance
方法,如下所示:
// Class<E> object will be used to create new instances
private final Class<E> stateClass;
// Users will pass the class to StateMachine's constructor
public StateMachine(Entity entity, Class<E> stateClass) {
this.entity = entity;
this.stateClass = stateClass;
states = new ArrayMap<S, E>();
}
Now you can create new state objects as follows: 现在,您可以如下创建新的状态对象:
E state = stateClass.newInstance(); // Only parameterless constructors are supported
state.setEntity(entity);
How can I ensure that the returned value is casted to proper parameterized type?
如何确保将返回值转换为正确的参数化类型?
This is not the question you should ask. 这不是您应该问的问题。 The real question is,
真正的问题是
How can I create an instance of a type parameter?
如何创建类型参数的实例?
And the answer, of course is, "no way". 答案当然是“没有办法”。 You need a workaround, these are some ideas:
您需要一种解决方法,这些是一些想法:
Class<YourType>
so the instance can be created reflectively. Class<YourType>
的实例,以便可以反射地创建该实例。 YourType
. YourType
对象。 YourType
, define a method like newInstance
on it and use it as a factory of more objects of the same type. YourType
的实例,在其上定义类似newInstance
的方法,并将其用作包含更多相同类型对象的工厂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.