As you will see below. I am writing a class named Property that can be bound to any Serializable type as evident from the class description.
Now the value in the property is auto bound to be of type T during compilation.
I want to implement a Class getType() method that should return the Class object of the value at runtime i.e.
Property<String> p = new Property<String>();
Class<String> cl = p.getType();
Here I expect cl to be String.class. Of course one way is:
return value == null ? null : value.getClass();
The issue is it won’t reflect in the type returned and returns a raw type of Class object.
Ideally I want it to be of type 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;
}
}
It is not possible the way you are doing it due to type erasure. One consequence is that this the type that is used to instantiate the type parameter cannot be directly determined at runtime.
Here are a couple of alternatives:
1) Use getClass() to get the type of the value of the Property.
2) Explicitly pass the
Classobject for the actual type of T as constructor parameter. Note that the generic typing means that you can’t accidentally pass the wrongClassobjectThere is another approach (which probably won’t work here from a design perspective) where you reify the Property classes; e.g.
There are clever variations of this where the subclass of the generic class in an anonymous class, and/or you access the type parameter via
getClass().getTypeParameters(). But note that thegetTypeParameters()approach only works if you’ve extended a generic class with specific types for the type parameters.