是否可以直接调用注解中定义的函数?

问题描述 投票:0回答:1

我是Java初学者,正在研究注解。

下面是我的代码。

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyRuntimeAnnotation {
    String value() default "default value";
}

----

public class Main {
    
    public static void main(String[] args) {
        A a = new A();
        System.out.println(a.value()); // Error
    }
}

@MyRuntimeAnnotation
class A{
    public void test() {System.out.println("A");}
}

我试图推测为什么我的代码会由于以下原因而产生错误。看了多篇文章,据说注释处理器只能生成新的源文件,而不能修改现有文件。

基于我的假设:

@Retention(RetentionPolicy.SOURCE)
-> 编译时消失
@Retention(RetentionPolicy.CLASS)
-> 运行时不加载
@Retention(RetentionPolicy.RUNTIME)
-> 在运行时加载

从编译器的角度来看,

a.value()
只是B中未定义的方法。那么,如果我想使用Runtime注释,是使用反射提取信息的唯一选择吗?

java annotations
1个回答
0
投票

在您当前的代码中,您面临的问题是由于您尝试在类 A 的实例上调用方法 value() 。但是, value() 不是类 A 的方法;它是一个方法。它是注释 @MyRuntimeAnnotation 的方法。

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class Main {
    
    public static void main(String[] args) {
        A a = new A();
        
        Class<?> aClass = a.getClass();
        MyRuntimeAnnotation annotation = aClass.getAnnotation(MyRuntimeAnnotation.class);
        
        if (annotation != null) {
            String value = annotation.value();
            System.out.println("Annotation value: " + value);
        } else {
            System.out.println("Annotation not found");
        }
    }
}

@MyRuntimeAnnotation
class A {
    public void test() {
        System.out.println("A");
    }
}

此代码使用反射来访问类 A 上的注释并检索注释的 value 元素的值。

当您想要从运行时注释访问值时,通常使用反射来检索这些值

© www.soinside.com 2019 - 2024. All rights reserved.