学习Java的反射机制和Annotation
1、创建一个Annotation类JavaAnnotation.java。
import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface JavaAnnotation {String value(); }
import java.lang.reflect.Field;import java.lang.reflect.Method;/** * 学习java的反射机制 * * @author sunny * */public class ReflectTest {@JavaAnnotation("字段注释")public String field1;private String filed2;public String getFiled2() {return filed2;}public void setFiled2(String filed2) {this.filed2 = filed2;}public String getField1() {return field1;}public void setField1(String field1) {this.field1 = field1;}private void act() {System.out.println("do nothing here......");}public static void main(String[] args) {try {Class a = Class.forName("ReflectTest");// 列举该类的所有字段Field[] fileds = a.getDeclaredFields();for (int i = 0; i < fileds.length; i++) {System.out.println(i + " - " + fileds[i].toString());}System.out.println("////////////////////字段列举完毕");// 列举该类的所有方法Method[] methods = a.getDeclaredMethods();for (int i = 0; i < methods.length; i++) {System.out.println(i + " - " + methods[i].toString());}System.out.println("////////////////////方法列举完毕");// 调用类方法try {// 通过默认构造方法创建一个新的实例对象Object instance = a.getConstructor(new Class[] {}).newInstance(new Object[] {});Method m = a.getDeclaredMethod("act");m.invoke(instance, new Object[] {});System.out.println("////////////////////方法调用完毕");} catch (Exception e) {e.printStackTrace();}// 操作Annotationtry {Field f = a.getDeclaredField("field1");if (f.isAnnotationPresent(JavaAnnotation.class))System.out.println("JavaAnnotation of field1 is '"+ f.getAnnotation(JavaAnnotation.class).value()+ "'");} catch (Exception e) {e.printStackTrace();}} catch (ClassNotFoundException e2) {e2.printStackTrace();}}}