自己寫的一個小例子,記錄一下。
package com.lxq.annotationAndreflection;public class Person{String name="default";Integer age=0;public Person(){super();}public Person(String name, Integer age){super();this.name = name;this.age = age;}public String getName(){return name;}public void setName(String name){this.name = name;}public Integer getAge(){return age;}public void setAge(Integer age){this.age = age;}}
package com.lxq.annotationAndreflection;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;@Retention(RetentionPolicy.RUNTIME)public @interface SelfAnnotation{String name();}
package com.lxq.annotationAndreflection;public class Injection{@SelfAnnotation(name = "Person")static Person person;public void show(){System.out.println(person.getName()+","+person.getAge());}}
package com.lxq.annotationAndreflection;import java.lang.annotation.Annotation;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;public class Test{public static void main(String[] args) throws Exception{//取得Injection的類描述類Class<Injection> clazz=Injection.class;//取得所有的欄位描述對象Field[] fields=clazz.getDeclaredFields();System.out.println(fields.length);for(Field field:fields){//取得每個欄位上面的註解對象Annotation[] annotations=field.getDeclaredAnnotations();System.out.println(annotations.length);for(Annotation annotation:annotations){//判斷註解對象是不是SelfAnnotation類型的if(annotation.annotationType()==SelfAnnotation.class){System.out.println("yes");//通過SelfAnnotation的name擷取要使用的beanNameString beanName=((SelfAnnotation) annotation).name();//產生一個Peron的類描述類Class<?> cc=Class.forName("com.lxq.annotation."+beanName);//產生一個Person對象Object ob=cc.newInstance();System.out.println(field.getName());//通過此方法將建立的執行個體對象賦值給 static Peron person//如果是非static,那麼set的第一個參數必須指定執行個體對象,也就是哪個Injection對象field.set(null, ob);//擷取名字為show的方法Method method=clazz.getDeclaredMethod("show");//調用該方法method.invoke(clazz.newInstance());//基本和上面的一樣,只是產生Person對象時,反射調用了帶參數的構造Class<?> c2=Class.forName("com.lxq.annotation."+beanName);Class<?>[] ptype=new Class[]{String.class,Integer.class};Constructor<?> ctor=c2.getConstructor(ptype);Object[] obj=new Object[]{new String("lxq"),new Integer(25)};Object object=ctor.newInstance(obj);field.set(null, object);Method method2=clazz.getDeclaredMethod("show");method2.invoke(clazz.newInstance());}}}//因為 static Peron person,所以建立的Injectin對象的Peron對象都是通過反射最後賦值過得Injection injection=new Injection();System.out.println(injection.person.getName()+","+injection.person.getAge());}}