Java – sun codemodel generic method
•
Java
Does anyone know how to generate the following generic method declarations using codemodel:
public <T> T getValue(Class<T> clazz){...}
Usage:
ValueType value = getValue(ValueType.class);
It does not seem to be handled by the existing implmentation
I know I can handle the code as follows, but it requires a cast:
public Object getValue(Class class){...}
Usage:
ValueType value = (ValueType)getValue(ValueType.class);
Obviously, it's a bit confusing because of the cast
Solution
Use the object return type to create a method, generate a method, and then overwrite the return type
final JDefinedClass exampleClass = codeModel._class( "com.example.ExampleClass" ); final JMethod method = exampleClass.method( JMod.PUBLIC,Object.class,"getValue" ); final JTypeVar t = method.generify( "T" ); method.type( t ); method.param( codeModel.ref( Class.class ).narrow( t ),"type" ); method.body()._return(JExpr._null());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码