註解的簡單示例

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章