反射

//打印类中的所有方法
public static void main(String[] args) throws ClassNotFoundException {
String className = "java.util.Scanner";
Class<?> cl = Class.forName(className);
while (cl != null){
for (Method m:cl.getDeclaredMethods()){
System.out.println(
Modifier.toString(m.getModifiers()) + " " +
m.getReturnType().getCanonicalName() + " " +
m.getName() +
Arrays.toString(m.getParameters())
);
}
cl = cl.getSuperclass();
}


//打印类中的所有字段
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException {
People p1 = new People();
p1.setName("张三");
p1.setAge(30);
printField(p1);

People p2 = new People();
p2.setName("李四");
p2.setAge(3);
printField(p2);
}
private static void printField(Object obj) throws IllegalAccessException {
for (Field f : obj.getClass().getDeclaredFields()) {
f.setAccessible(true);
Object value = f.get(obj);
System.out.println(f.getName() + ":" + value);
}
}
原文地址:https://www.cnblogs.com/zj1234/p/8623984.html