我可以在编译时从 TypeVariable 或 VariableElement 到基础类上的方法列表在注释处理器中吗 [英] Can I get from a TypeVariable or VariableElement to a list of Methods on the underlying class In an annotation processor at compile time

查看:19
本文介绍了我可以在编译时从 TypeVariable 或 VariableElement 到基础类上的方法列表在注释处理器中吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带注释的类:

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;     
    }
}

在我的注解处理器中,我想获取传递给 setMessage 方法的 Object 上的 getter 方法列表,然后这些信息将用于代码生成.

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.

我扩展了 ElementScanner6 并设法获得了一个似乎包含参数的 VariableElement,但我不知道从哪里开始.

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.

所以在这个例子中,我想在编译时获取 TestMessage 类中的所有方法.

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

任何想法

推荐答案

注解处理比较麻烦,而且会很快迷路..到这种类型,然后获取其成员并对其进行过滤.尝试使用以下代码,让我知道它是否有效:

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

我认为它应该可以工作,但不能 100% 确定它是一个 getter,因为您无法检查方法体内部做了什么.我假设getter"是指以get"开头且没有参数的方法.

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 ?

这篇关于我可以在编译时从 TypeVariable 或 VariableElement 到基础类上的方法列表在注释处理器中吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆