8

有谁知道如何使用 CodeModel 生成以下通用方法声明?

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

用法:

ValueType value = getValue(ValueType.class);

似乎没有被现有的实现处理。

我知道我可以按如下方式处理代码,但它需要强制转换:

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

用法:

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

显然,由于演员阵容,这有点混乱。

4

1 回答 1

12

使用返回类型创建方法Object,生成方法,然后覆盖返回类型。

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());
于 2012-04-30T08:26:42.513 回答