2016-10-27 52 views
1

爲了方便的原因,我想要在一個新的生成的類中合併多個類中的靜態方法。將靜態方法與註釋處理和javapoet合併

我正在使用註釋處理和javapoet。

我的問題:從註釋處理中,我得到了靜態方法作爲ExecutableElements的列表。

對於JavaPoet,我需要創建那些的MethodSpecs。我正在嘗試:

public MethodSpec apply(@Nullable ExecutableElement input) { 
    TypeMirror returnType = input.getReturnType(); 

    return MethodSpec.methodBuilder(THE_METHOD_NAME) 
    .addModifiers(Modifier.PUBLIC, Modifier.STATIC) 
    .returns(THE_RETURN_TYPE) 
    .addParameter(EVERY_PARAMETER_WITH_TYPE_AND_NAME) 
    .addStatement("$T.$S($S)", THE_ENCLOSING_CLASS, THE_METHOD_NAME, THE_PARAMETERS) 
    .build(); 
} 

我的問題:如何獲取CAPS中丟失單詞的類型值?看起來像ExecutableElements不像行爲反射api。

回答

0

這可能是一個示意性的代碼,你可以用它來讓你開始:

THE_METHOD_NAME - >input.getSimpleName()

THE_RETURN_TYPE - >input.getReturnType()

THE_ENCLOSING_CLASS - >input.getEnclosingElement().getSimpleName()

EVERY_PARAMETER_WITH_TYPE_AND_NAME - >

for (VariableElement ve: executableElement.getParameters()){ 
    System.out.println("Param name: " + ve.getSimpleName()); 
    // note here that the type can be generic, so you'll need to parse 
    // the generic part and use to build a javapoet 
    // ParameterizedTypeName 
    System.out.println("Param type: " + ve.asType()); 
} 
+0

謝謝。但正如你在上面的代碼中看到的那樣,getReturnType是「TypeMirror」類型的......如果我將它傳遞給javapoet,我將得到一個TypeMirror return ... –

+0

'com.squareup.javapoet.ClassName'可用於構建從've.asType()'的輸出的字符串表示中提取一個類型。基於從[javapoet](https://github.com/square/javapoet)獲取的示例代碼,我在編寫時假定了這一點, –