如何最好地编码以下内容?它可行吗?请参阅说明

Gau*_*tam 0 java coding-style

正如您将在下面看到的.我正在编写一个名为Property的类,它可以绑定到任何Serializable类型,从类描述中可以看出.

现在,属性中的值在T编译期间自动绑定为类型.

我想实现一个Class getType()方法,该方法应该Class在运行时返回值的对象,即

Property<String> p = new Property<String>();

Class<String> cl = p.getType(); 
Run Code Online (Sandbox Code Playgroud)

在这里,我希望cl是String.class.当然有一种方法是:

return value == null ? null : value.getClass();
Run Code Online (Sandbox Code Playgroud)

问题是它不会反映在返回的类型中并返回原始类型的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Boh*_*ian 6

简而言之,您不能,因为在运行时类型已被删除.

但是,你可以这样做(缩写为相关代码):

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
    }
Run Code Online (Sandbox Code Playgroud)

Class<T>传递给构造函数的对象通常称为"类型标记".