getField获得类中指定的public属性;getDeclaredField返回指定类中指定的属性(任何可见性)。看下面一个简单的例子:
- package com;
- import java.lang.reflect.Field;
- import java.util.*;
- public class MyUtil {
- public static void main(String[] args) {
- testFields();
- }
- public static void testFields() {
- try {
- System.out.println("Declared fields: ");
- Field[] fields = Dog.class.getDeclaredFields();
- for(int i = 0; i < fields.length; i++) {
- System.out.println(fields[i].getName()); // 此处结果是color, name, type, fur
- }
- System.out.println("Public fields: ");
- fields = Dog.class.getFields();
- for(int i = 0; i < fields.length; i++) {
- System.out.println(fields[i].getName()); // 此处结果是color, location
- }
- Dog dog = new Dog();
- dog.setAge(1);
- Method method = dog.getClass().getMethod("getAge", null);
- Object value = method.invoke(dog);
- System.out.println(value); // 此处结果是1
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- class Dog extends Animal {
- public int color;
- protected int name;
- private int type;
- int fur;
- }
- class Animal {
- public int location;
- protected int age;
- private int height;
- int length;
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
可见,getDeclaredField可以获得类中任何可见性的属性不包括基类,而getField只能获得public属性包括基类的public属性。如果需要获取基类某个非public属性的值,则只能通过反射来调用方法了,从上述code可以看到。注意,getField只能得到public方法。