package gr.annotation;
import java.lang.reflect.Method;
import java.lang.annotation.*;
import java.util.Arrays;
//仅存在于源代码
//@Retention(RetentionPolicy.SOURCE)
//仅存在于字节码
//@Retention(RetentionPolicy.CLASS)
//运行时可见, 可以进行反射来访问注解属性
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomNotification {
// 只能用基本类型,String,或者数组
// 使用default定义默认值,这样在使用本注解时,不对本属性赋值也不会报错.
int age() default 25;
String name() default "Dummy";
boolean isReady() default false;
// 数组的赋值方法
double[] power() default { 0.618, 1.414, 107.1 };
// 仅存在value属性时,value可省写,但是这里value不是唯一属性
long value() default 2341352435L;
}
/**
*
* @author Boki
* 使用注解
*/
class ForFun {
// 对于没有默认值的,不可省写
@CustomNotification(name = "Nicol Bolas", age = 53366, isReady = true, power = { 23.5, 565.7,
34 })
public void eat() throws NoSuchMethodException, SecurityException {
Method method = ForFun.class.getMethod("eat", null);
// 通过反射泛型获得注解对象
CustomNotification annotation = method.getAnnotation(CustomNotification.class);
if (annotation == null) {
System.out.println("annotation is Null");
return;
}
System.out.println(annotation.age());
System.out.println(annotation.name());
System.out.println(annotation.isReady());
System.out.println(Arrays.toString(annotation.power()));
System.out.println(annotation.value());
}
public static void main(String[] args) throws Exception {
new ForFun().eat();
}
}
注解的简单示例
最新推荐文章于 2025-01-07 12:26:40 发布


3779

被折叠的 条评论
为什么被折叠?



