Java通过反射获取Fields、Method、Constructor示例
1. getFields()和getDeclaredFields()
- getFields能获取该类和父类(包括Object)public的属性,getDeclaredFields获取该类public和private的属性
2. getMethods()和getDeclaredMethods()
- getMethods能获取该类和父类(包括Object)public的方法,getDeclaredMethods获取该类public和private的方法
3. getConstructors()和getDeclaredConstructors()
- getConstructors能获取该类public的构造方法,getDeclaredConstructors获取该类public和private的构造方法
示例代码:
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class TestReflection {
public static void main(String[] args) throws ClassNotFoundException {
Class c = Class.forName("Son");
// 能获取该类和父类public的属性
for (Field field : c.getFields()) {
System.out.println(field);
}
System.out.println("====================");
// 获取该类public和private的属性
for (Field field : c.getDeclaredFields()) {
System.out.println(field);
}
System.out.println("====================");
// 能获取该类和父类public的方法
for (Method method : c.getMethods()) {
System.out.println(method);
}
System.out.println("====================");
// 获取该类public和private的方法
for (Method method : c.getDeclaredMethods()) {
System.out.println(method);
}
System.out.println("====================");
// 能获取该类public的构造方法
for (Constructor constructor : c.getConstructors()) {
System.out.println(constructor);
}
System.out.println("====================");
// 获取该类public和private的构造方法
for (Constructor declaredConstructor : c.getDeclaredConstructors()) {
System.out.println(declaredConstructor);
}
}
}
class Son extends father {
public String s1;
private String s2;
public String method1() {
return "method1";
}
private String method2() {
return "method2";
}
public Son() {
}
private Son(String test) {
}
}
class father {
public String s11;
private String s22;
public String method11() {
return "method11";
}
private String method22() {
return "method22";
}
public father() {
}
private father(String test) {
}
}
结果: