I want to use Java Generics feature to implement a common functionality. But I don't know hot to get a java.lang.reflect.Type object for a self-defined class object. Following is my case that I want to get a Type from a given class name and pass it to ProcessedResult<T> to replace T:
String className = getClassName();
Class clazz = Class.forName(className);
Type type = null;
ProcessedResult<T> result = new ProcessedResult<T>();
I try to use ProductModel.class.getGenericSuperclass(), but as its name, it only return Type of its super class.
Can anybody gives me help? Thanks.
You cannot specify a runtime-determined type as a compile time substitution for a generic type.
Your type T is actually only enforced at compile time because of type erasure. So by the time you have an actual type at runtime, any information or checks are already done and gone.
Your ProcessedResult will have to work with a Class<T> or Type object instead to do any useful work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With