java註解的基本操作(java註解用代碼的基本實現)

這裏只例舉了在方法上的註解操作,其他方面與此操作類似,我就不多提了,想深入瞭解可以查資料或者看書哈,具體看代碼如何實現吧。

我編寫的註解處理器代碼爲:



被測試的類內容如下:




代碼實現如下:


package com.jiaxun.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class AnnotationDemo {
	//通過註解來實現方法調用
	public static void annotationTest1()throws Exception{
		Class clazz = Class.forName("com.jiaxun.annotation.TestClass");
		TestClass newInstance = (TestClass)clazz.newInstance();
		for (Method method : clazz.getMethods()) {
			for (Annotation annotation : method.getAnnotations()) {
			String annotationName = annotation.annotationType().getSimpleName();
			String annotationFieldName = ((Test) annotation).name();
			if(annotationFieldName.equals("zengjiaxun"))
				method.invoke(newInstance);
			}
		}
	}
	//通過註解屬性值來實現方法調用
	public static void annotationTest2()throws Exception{
		Class clazz = Class.forName("com.jiaxun.annotation.TestClass");
		TestClass newInstance = (TestClass)clazz.newInstance();
		for (Method method : clazz.getMethods()) {
			Annotation[] annotations = method.getAnnotations();
			for (Annotation annotation : annotations) {
				String annotationName = ((Test)annotation).name();
				if(annotationName.equals("xun")){
					method.invoke(newInstance);
				}
			}
		}
	}
	public static void main(String[] args) throws Exception {
		annotationTest1();
		annotationTest2();
	}
}

輸出結果爲



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