Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sun CodeModel generic method

Does anyone know how to generate the following generic method declaration using CodeModel?

public <T> T getValue(Class<T> clazz){...}

usage:

ValueType value = getValue(ValueType.class);

Seems not to be handled by the existing implementation.

I know I could handle the code as follows, but it requires a cast:

public Object getValue(Class class){...}

usage:

ValueType value = (ValueType)getValue(ValueType.class);

Obviously, this is a bit messy because of the cast.

like image 349
John Ericksen Avatar asked Feb 20 '12 01:02

John Ericksen


1 Answers

Create the method with an Object return type, generify the method, 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());
like image 178
ajlane Avatar answered Oct 31 '22 09:10

ajlane