8

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.

colourCoder
  • 1,394
  • 2
  • 11
  • 18
John Ericksen
  • 10,995
  • 4
  • 45
  • 75
  • Interesting, just found a bug report that mentions this issue: http://java.net/jira/browse/CODEMODEL-4 . Plus, this was commented on recently. – John Ericksen Feb 20 '12 at 16:53

1 Answers1

12

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());
John Ericksen
  • 10,995
  • 4
  • 45
  • 75
ajlane
  • 1,899
  • 1
  • 18
  • 23
  • This works like a charm. Thank you so much for setting me on the right path. I've taken the liberty of updating the referenced jira issue. – John Ericksen May 01 '12 at 02:53