十、获取运行时类的结构
作者:互联网
通过反射获取运行时类的完整结构
Field、Method、Constructor、Superclass、Interface、Annotation
public class Demo07 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class clazz = Class.forName("com.zx.reflection.User");
//1. 类名
System.out.println(clazz.getName()); //包名+类名
System.out.println(clazz.getCanonicalName());//包名+类名
System.out.println(clazz.getTypeName());//包名+类名
System.out.println(clazz.getSimpleName());//类名
System.out.println("=========================================");
//2. 属性
// System.out.println(clazz.getField("id")); //只能找到public修饰的指定属性
System.out.println(clazz.getDeclaredField("id")); //能找到指定属性
//只能找到所有public属性
for (Field field : clazz.getFields()) {
System.out.println(field);
}
//能找到所有属性
for (Field field : clazz.getDeclaredFields()) {
System.out.println(field);
}
System.out.println("=========================================");
//2. 方法
//获取所有public的方法,包括父类的public方法
System.out.println("************");
for (Method method : clazz.getMethods()) {
System.out.println(method);
}
//获取本类所有的方法
System.out.println("-----------");
for (Method method : clazz.getDeclaredMethods()) {
System.out.println(method);
}
System.out.println("-----------");
//public
System.out.println(clazz.getMethod("getId", null));
//all
System.out.println(clazz.getDeclaredMethod("getId", null));
//public
System.out.println(clazz.getMethod("setId", Integer.class));
//all
System.out.println(clazz.getDeclaredMethod("setId", Integer.class));
//public
for (Constructor constructor : clazz.getConstructors()) {
System.out.println(constructor);
}
//all
for (Constructor declaredConstructor : clazz.getDeclaredConstructors()) {
System.out.println(declaredConstructor);
}
}
}
标签:System,clazz,获取,类名,println,时类,public,运行,out 来源: https://www.cnblogs.com/epiphany8/p/16367216.html