站点图标 度崩网-几度崩溃

Class类的getDeclaredFields()与getFields()方法的区别?

 

测试代码:

package constxiong.interview;

import java.lang.reflect.Field;

/**
 * 测试通过 Class 获取字段
 * @author ConstXiong
 */
public class TestGetFields 
		extends TestGetFieldsSub implements TestGetFieldsInterface{
	private String privateFieldSelf;
	protected String protectedFieldSelf;
	String defaultFieldSelf;
	public String publicFieldSelf;
	
	
	public static void main(String[] args) {
		System.out.println("--------  getFields  --------");
		for (Field field : TestGetFields.class.getFields()) {
			System.out.println(field.getName());
		}
		
		System.out.println("--------  getDeclaredFields  --------");
		for (Field field : TestGetFields.class.getDeclaredFields()) {
			System.out.println(field.getName());
		}
	}
}

class TestGetFieldsSub {
	private String privateField;
	protected String protectedField;
	String defaultField;
	public String publicField;
}

interface TestGetFieldsInterface {
	String interfaceField = "";
}

 

打印:

--------  getFields  --------
publicFieldSelf
interfaceField
publicField
--------  getDeclaredFields  --------
privateFieldSelf
protectedFieldSelf
defaultFieldSelf
publicFieldSelf