Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle generics inside a Java "annotation processor"?

I asked before for an example "annotation processor" that would generate a Proxy/Delegate for an interface, but got no answer, and did not find anything on the Internet, so I made my own.

So far it worked well, until I tried to use generics inside a super-interface. If I use generics in the annotated interface, it works fine (more by accident than by design). But if the annotated interface extends another interface that takes a generic type parameter, that parameter is not "bound" to the type that the annotated interface use when extending the super-interface. Example:

public interface TestFragment<E> {
    void test(E dummy);
}
@CreateWrapper
public interface TestService extends TestFragment<String> {
    double myOwnMethod();
}

This would generate:

// ...
public void test(final E dummy) {
    wrapped.test(dummy);
}
// ...

instead of the correct:

// ...
public void test(final String dummy) {
    wrapped.test(dummy);
}
// ...

The code that generates the parameters in the generated methods look like this:

int count = 0;
for (VariableElement param : method.getParameters()) {
    if (count > 0) {
        pw.print(", ");
    }
    count++;
    pw.printf("final %s %s", param.asType().toString(),
        param.getSimpleName().toString());
}

Is there a way to do this?

like image 534
Sebastien Diot Avatar asked Sep 28 '11 20:09

Sebastien Diot


1 Answers

Have a look at http://docs.oracle.com/javase/6/docs/api/javax/lang/model/util/Types.html#asMemberOf%28javax.lang.model.type.DeclaredType,%20javax.lang.model.element.Element%29

Might be helpful. I used it to solve a very similar problem.

like image 63
Ryan Walls Avatar answered Sep 21 '22 06:09

Ryan Walls