Java反射 getField和getDeclaredField区别

getField获得类中指定的public属性;getDeclaredField返回指定类中指定的属性(任何可见性)。看下面一个简单的例子:

Java代码   收藏代码
  1. package com;    
  2.     
  3. import java.lang.reflect.Field;    
  4. import java.util.*;    
  5.     
  6. public class MyUtil {    
  7.     
  8.     public static void main(String[] args) {    
  9.        testFields();    
  10.     }    
  11.         
  12.     public static void testFields() {    
  13.         try {    
  14.             System.out.println("Declared fields: ");    
  15.             Field[] fields = Dog.class.getDeclaredFields();    
  16.             for(int i = 0; i < fields.length; i++) {    
  17.                 System.out.println(fields[i].getName()); // 此处结果是color, name, type, fur    
  18.             }    
  19.                 
  20.             System.out.println("Public fields: ");    
  21.             fields = Dog.class.getFields();    
  22.             for(int i = 0; i < fields.length; i++) {    
  23.                 System.out.println(fields[i].getName()); // 此处结果是color, location    
  24.             }    
  25.     
  26.             Dog dog = new Dog();    
  27.             dog.setAge(1);    
  28.             Method method = dog.getClass().getMethod("getAge"null);    
  29.             Object value = method.invoke(dog);    
  30.             System.out.println(value); // 此处结果是1    
  31.         } catch (Exception e) {    
  32.             e.printStackTrace();    
  33.         }    
  34.     }    
  35.     
  36. }    
  37.     
  38. class Dog extends Animal {    
  39.     public int color;    
  40.     protected int name;    
  41.     private int type;    
  42.     int fur;    
  43. }    
  44.     
  45. class Animal {    
  46.     public int location;    
  47.     protected int age;    
  48.     private int height;    
  49.     int length;     
  50.     
  51.     public int getAge() {    
  52.         return age;    
  53.     }    
  54.     
  55.     public void setAge(int age) {    
  56.         this.age = age;    
  57.     }    
  58. }    

 可见,getDeclaredField可以获得类中任何可见性的属性不包括基类,而getField只能获得public属性包括基类的public属性。如果需要获取基类某个非public属性的值,则只能通过反射来调用方法了,从上述code可以看到。注意,getField只能得到public方法。

猜你喜欢

转载自tommy-lu.iteye.com/blog/2221678