反射二(字段)
1.Filed:封装了字段的信息,获取字段
@Test public void test4() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException { Class clazz = Class.forName("reflect.Person"); //获取字段,仅能获取public,包括自己和父类的 Field[] fields = clazz.getFields(); for (int i = 0; i < fields.length; i++) { System.out.println(fields[i]); } //仅能获取当前类的字段包括私有的 Field[] fields1 = clazz.getDeclaredFields(); for (int i = 0; i < fields1.length; i++) { System.out.println(fields1[i]); } //获取指定名字的字段 Field field = clazz.getField("age"); System.out.println(field); Person person= new Person(1,"xiaoming",1); //获取指定对象指定Field的值 Object obj = field.get(person); //输出字段age的值 System.out.println(obj); //设置指定对象指定字段的值 field.set(person,2); System.out.print(person.getAge()); //若属性字段是私有的,name是私有的 Field field1 = clazz.getDeclaredField("name"); System.out.print(field1); field1.setAccessible(true);//设置可访问 Object obj1 = field1.get(person); //输出字段age的值 System.out.println(obj1); }
2.获取构造器,构造器在实际中使用较少
//获取构造器 @Test public void test() throws ClassNotFoundException { Class clazz = Class.forName("reflect.Person"); Constructor[] cons = clazz.getConstructors(); for(Constructor con:cons){ System.out.println(con); } }
3.注解
(1)创建注解
(2)注解方法
/* *注解 */ @Retention(RetentionPolicy.RUNTIME)//运行时可见 @Target(value={ElementType.METHOD})//范围:方法上面 public @interface AgeValidator { public int max(); public int min(); }
(3)对象的字段设置
@AgeValidator(min=0,max=100) public void setAge(int age) { this.age = age; }
(3)测试
//注解 @Test public void testAnnotation() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { //假设要给对象的某一字段设置一个范围例如:Person中的age的范围为0-100 //1.创建注解 Class clazz = Class.forName("reflect.Person"); Object obj = clazz.newInstance(); Method method = clazz.getDeclaredMethod("setAge",int.class); int age = 200; //2.获取注解 Annotation annotation = method.getAnnotation(AgeValidator.class); if(annotation!=null){ //进行判断 // if(age>100||age<0){ // throw new RuntimeException("年龄不合法"); // } //通过注解的方法设置 if(((AgeValidator) annotation).max()<age||((AgeValidator) annotation).min()<age){ throw new RuntimeException("年龄不合法"); } } method.invoke(obj,age); }