注解的简单示例

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();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值