正如您将在下面看到的。我正在编写一个名为 Property 的类,从类描述中可以明显看出,该类可以绑定(bind)到任何可序列化类型。
现在属性中的值自动绑定(bind)为 T
类型编译期间。
我想实现 Class getType()
应该返回 Class
的方法运行时值的对象,即
Property<String> p = new Property<String>();
Class<String> cl = p.getType();
这里我期望 cl 是 String.class。当然一种方法是:
return value == null ? null : value.getClass();
问题是它不会反射(reflect)在返回的类型中,并返回原始类型 Class
目的。
理想情况下,我希望它的类型为 Class<String>
public class Property<T extends Serializable> implements Serializable {
private T value = null ;
private String name = null ;
private boolean dirty = false ;
private Entity parent = null ;
public Class getType() {
// Here I want to determine the type of T that this object is bound to ?
return class;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isDirty() {
return dirty;
}
public void setDirty(boolean dirty) {
this.dirty = dirty;
}
public Entity getParent() {
return parent;
}
public void setParent(Entity parent) {
this.parent = parent;
}
}
最佳答案
简而言之,你不能,因为在运行时类型已是 erased .
但是,您可以这样做(缩写为相关代码):
public class Property<T extends Serializable> implements Serializable {
private T value = null;
private final Class<T> clazz;
// The constructor requires an instance of the Class<T>
public Property(Class<T> clazz) {
this.clazz = clazz;
}
// Return a typed Class object
public Class<T> getType() {
return clazz; // echo back a typed Class object pass to the constructor
}
Class<T>
传递给构造函数的对象通常称为“类型标记”。
关于java - 如何最好地编写以下代码?可行吗?请看说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11966940/