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

18次阅读
没有评论

共计 849 个字符,预计需要花费 3 分钟才能阅读完成。

在 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

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-05-27发表,共计849字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)