Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get java.lang.Type object of a self-defined class object?

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.

like image 380
Brady Zhu Avatar asked Nov 02 '25 14:11

Brady Zhu


1 Answers

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.

like image 136
Steven Schlansker Avatar answered Nov 05 '25 04:11

Steven Schlansker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!