I am trying to write a class that takes a parameter name and can return the corresponding parameter of this object. Currently, my class is as follows:
public class ParamValue<T> {
private String paramName;
@SuppressWarnings("unchecked")
public T getValue(Object obj) throws Exception {
Class<?> c = obj.getClass();
Field param = c.getDeclaredField(paramName);
boolean isAccessible = param.isAccessible();
param.setAccessible(true);
Object value = param.get(obj);
param.setAccessible(isAccessible);
return (T) value;
}
}
Now imagine that we have an object with a simple long parameter:
public class ExampleClass {
private Long value;
}
We can do this to return a long value:
ExampleClass ec = new ExampleClass();
ec.setValue(12L);
ParamValue<Long> pvString = new ParamValue<>();
pvString.setParamName("value");
System.out.println(pvString.getValue(ec));
Now, if I declare "ParamValue" as a point, for example, it still works:
ExampleClass ec = new ExampleClass();
ec.setValue(12L);
ParamValue<Point> pvPoint = new ParamValue<>();
pvPoint.setParamName("value");
System.out.println(pvPoint.getValue(ec));
But, since Point cannot be attributed to Long, I expected some exception, for example ClassCastException.
I know that the java compiler does some type erasure during compilation, but I thought that the compiler will automatically try to pass to Point and play on the output "pvPoint.getValue (ec)"
Can someone explain how this works?
thank