gpt4 book ai didi

JavaParser 添加通用类型作为方法返回类型

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:03:25 27 4
gpt4 key购买 nike

我正在使用 javaparser-1.0.8 并尝试生成以下通用方法。

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) {
}

最佳答案

我有一个类似的案例(但不完全是)。我想生成

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

关于JavaParser 添加通用类型作为方法返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25552064/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com