使用注释处理器获取方法的返回值

发布于 2025-01-26 13:19:39 字数 456 浏览 2 评论 0原文

我是注释处理器的新手,我想知道是否有可能在注释处理过程中获得带注释的方法的返回值。例如,我有注释

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Parameters {}

,我有一个标记了此注释的类:

@Parameters
public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][] {
            { 0, 0, 0 }, { 1, 1, 2 }
    });
}

是否有可能获得new Object [] [] {{0,0,0,0},{1,1,1,2}}使用注释处理工具(APT)?

I am new to annotation processor, I wonder if it is possible to get the the return value of a method marked with annotations during annotation processing. For example, I have annotation

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Parameters {}

and I have a class marked with this annotation:

@Parameters
public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][] {
            { 0, 0, 0 }, { 1, 1, 2 }
    });
}

is it possible I get new Object[][] { { 0, 0, 0 }, { 1, 1, 2 } } using annotation processing tool(apt)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海风掠过北极光 2025-02-02 13:19:39

是的,您可以 Indoke 反射通过过滤在您的班级中可用的方法列表中,并用您的自定义注释注释。您的代码看起来像这样:

Object[][] objectArray; // should be initialize
Class<?> clazz = object.getClass();
for (Method method : clazz.getDeclaredMethods()) {
    if (method.isAnnotationPresent(Parameters.class)) {
        objectArray = method.invoke(object);
    }
}

return objectArray;

其中对象是包含您方法的类的实例。

Yes, you can invoke your method with reflection by filtering on the list of methods available in your class and annotated with your custom annotation. Your code will look something like this:

Object[][] objectArray; // should be initialize
Class<?> clazz = object.getClass();
for (Method method : clazz.getDeclaredMethods()) {
    if (method.isAnnotationPresent(Parameters.class)) {
        objectArray = method.invoke(object);
    }
}

return objectArray;

Where object is an instance of your class containing the your method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文