温馨提示×

java注解如何实现变量参数传递

小亿
93
2024-05-14 09:29:15
栏目: 编程语言

在Java中,可以使用注解来实现变量参数传递。以下是一个简单的示例:

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation {
    String value() default "";
}

public class MyClass {
    @MyAnnotation(value = "Hello")
    private String message;

    public String getMessage() {
        return message;
    }

    public static void main(String[] args) {
        MyClass obj = new MyClass();
        Class<?> clazz = obj.getClass();
        for (java.lang.reflect.Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(MyAnnotation.class)) {
                MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);
                String value = annotation.value();
                try {
                    field.setAccessible(true);
                    field.set(obj, value);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(obj.getMessage()); // Output: Hello
    }
}

在上面的示例中,我们定义了一个自定义注解MyAnnotation,并将其应用于类的字段message上。通过反射,我们可以获取字段上的注解,并将注解中的值赋给字段。最终输出的结果为Hello

0