Can I get from a TypeVariable or VariableElement to a list of Methods on the underlying class In an annotation processor at compile time

我只是一个虾纸丫 提交于 2019-12-11 02:11:53

问题


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 ?



来源:https://stackoverflow.com/questions/6926632/can-i-get-from-a-typevariable-or-variableelement-to-a-list-of-methods-on-the-und

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!