Java反射【四、成员变量的反射和构造的反射】
获取一个类下所有字段信息
- Field[] fs = c.getFields(); 获取所有字段(public)
- Field[] fs = c.getDeclaredFields(); 获取所有声明字段
- Class c = f.getType(); 获取字段类型
- String s = f.getName(); 获取字段名称
Demo:
public static void printFieldsMsg(Object obj) {
Class c = obj.getClass();
//打印输出所有成员变量的信息
Field[] fs = c.getFields();
for (Field field : fs) {
Class type = field.getType();
String typeName = type.getSimpleName();
String name = field.getName();
System.out.println(typeName+" "+name);
}
}
获取构造信息
- Constructor[] cs = c.getConstructors(); 获取构造函数列表
Demo:
public static void printConMessage(Object obj){
Class c = obj.getClass();
Constructor[] cs = c.getConstructors();
for (Constructor constructor : cs) {
System.out.print(constructor.getName()+"(");
for (Class param : constructor.getParameterTypes()) {
System.out.print(param.getSimpleName()+",");
}
System.out.println(")");
}
}