Can I get from a TypeVariable or VariableElement t

2019-07-21 00:35发布

问题:

I have an annotated class:

public class CacheMessageHolder<TestMessage> implements MessageHolder<TestMessage> {
    protected @MessageHolderType TestMessage message;
    @Override
    @SendProtoAll (proto ="protoMessageClass", matchType=MatchType.PARTIAL)
    public void setMessage( TestMessage msg) {
        this.message = msg;     
    }
}

In my annotation processor I want to get a list of the getter methods on the Object passed into the setMessage method, this information will then be used for code generation.

I extend ElementScanner6 and manage to get a VariableElement that seems to hold the parameter but I do not know where to go from here.

So in this example I want to get all the methods in the TestMessage class at compile time.

Any ideas

回答1:

Annotation Processing is quite cumbersome, and one can get lost quite fast.. I think you should get the type corresponding to this parameter element, then get the element corresponding to this type, then get its members and filter them. Try to play with the following code, and let me know if it work :

VariableElement parameterElement;
ProcessingEnvironment processingEnv;

TypeMirror parameterType = parameterElement.asType();
Types typeUtils = processingEnv.getTypeUtils();
TypeElement typeElement = (TypeElement) typeUtils.asElement(parameterType);
Elements elementUtils = processingEnv.getElementUtils()
List<? extends Element> elementMembers = elementUtils.getAllMembers(typeElement);
List<ExecutableElement> elementMethods = ElementFilter.methodsIn(elementMembers);
for(ExecutableElement methodElement : elementMethods) {
    if (methodElement.getParameters().size()==0 && methodElement.getSimpleName().toString().startsWith("get")) {
      // do something
    }
}

I think it should work, but won't be sure 100% that it's a getter, since you can't check what's done inside a method body. I assumed by "getter" you meant a method starting with "get", and with no parameter.

Does that answer your question ?