Sun CodeModel generic method

筅森魡賤 提交于 2019-12-21 12:17:39

问题


Does anyone know to 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 implmentation.

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.


回答1:


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());


来源:https://stackoverflow.com/questions/9355160/sun-codemodel-generic-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!