2014-08-28 80 views
3

我正在使用javaparser-1.0.8,並試圖生成以下通用方法。JavaParser添加通用類型作爲方法返回類型

public <T extends SomeInterface> T get(int param) { 
    return (T) doSomeMagic(param); 
} 

我有以下代碼是應該構建方法:

public static void main(String[] args) throws Exception { 

    // creates an input stream for the file to be parsed 
    File mainActivity = new File("<path>/Main.java"); 
    FileInputStream in = new FileInputStream(mainActivity); 

    CompilationUnit cu; 
    try { 
     // parse the file 
     cu = JavaParser.parse(in); 
     addMethod(cu); 
    } finally { 
     in.close(); 
    } 

    // prints the resulting compilation unit to default system output 
    System.out.println(cu.toString()); 
} 

private static void addMethod(CompilationUnit cu) { 
     WildcardType wildcardType = new japa.parser.ast.type.WildcardType(ASTHelper.createReferenceType("SomeInterface", 0)); 
     MethodDeclaration method = new MethodDeclaration(ModifierSet.PUBLIC, wildcardType, "get"); 
     method.setModifiers(ModifierSet.addModifier(method.getModifiers(), ModifierSet.PUBLIC)); 
     Parameter param = ASTHelper.createParameter(ASTHelper.INT_TYPE, "id"); 
     ASTHelper.addParameter(method, param); 
     BlockStmt block = new BlockStmt(); 
     method.setBody(block); 
     ASTHelper.addMember(cu.getTypes().get(0), method); 
} 

輸出:

public ? extends SomeInterface get(int id) { 
} 
+0

我強烈建議遷移到2.3.0了JavaParser擁有該項目目前正在此處維護的Java 8 完整支持:HTTPS ://github.com/javaparser/javaparser 聲明:我是JavaParser提交者。 – 2015-11-17 23:43:17

回答

1

我有一個類似的情況下(但不完全相同)。我想產生

public Class<? extends SomeInterface> getSomeClass() { 
    return SomeImplementation.class; 
} 

,做的是這樣的:

Type w = new WildcardType(ASTHelper.createReferenceType("SomeInterface", 0)); 
ClassOrInterfaceType returnType = new ClassOrInterfaceType("Class"); 
ret.setTypeArgs(Arrays.asList(w)); 
MethodDeclaration mesthod = new MethodDeclaration(
    ModifierSet.PUBLIC, returnType, "getSomeClass"); 
+0

感謝您的回答,現在已經很長時間了,我甚至不記得我正在嘗試使用這個功能:P – ejohansson 2015-11-03 11:35:36

+0

就是那個答案,甚至是「可接受的」... :-) – towi 2015-11-03 12:19:59

+0

如果代碼正常工作,最不值得讚賞:) – ejohansson 2015-11-04 01:25:18