I'm using javaparser-1.0.8 and I'm trying to generate the following generic method.
public <T extends SomeInterface> T get(int param) {
return (T) doSomeMagic(param);
}
I have the following code that is supposed to build the method:
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);
}
output:
public ? extends SomeInterface get(int id) {
}
I had a similar case (but not exactly). I wanted to generate
public Class<? extends SomeInterface> getSomeClass() {
return SomeImplementation.class;
}
and did that like this:
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With