具体使用
try {
Class clazz =Class.forName("test.Person");
//1 创建对象
Person person = (Person)clazz.newInstance();
//2 获取属性对象,获取运行时类和所有父类中public的属性
Field[] fields = clazz.getFields();
//运行时类中的所有属性(不含父类)
Field[] fields1 = clazz.getDeclaredFields();
for(Field field:fields1){
//权限修饰符
Modifier.toString(field.getModifiers());
//类型
field.getType();
//变量名
field.getName();
}
//3 获取运行时类及其父类中所有public的方法
Method[] methods = clazz.getMethods();
//运行时类中的所有方法(不含父类)
Method[] methods1 = clazz.getDeclaredMethods();
for(Method method:methods){
//获取方法生成的注解(元注解Retention声明为RUNTIME才能获取到)
method.getAnnotations();
//权限修饰符
Modifier.toString(method.getModifiers());
//返回值类型
method.getReturnType().getName();
//方法名称
method.getName();
//获取形参列表
Class[] parameterTypes = method.getParameterTypes();
for(Class parameterType:parameterTypes){
parameterType.getName();
}
//抛出的异常
Class[] exceptionTypes = method.getExceptionTypes();
for(Class exceptionType:exceptionTypes){
exceptionType.getName();
}
}
//4 获取当前运行时类声明为public的构造器
Constructor[] constructors= clazz.getConstructors();
//获取当前运行时类所有的构造器
clazz.getDeclaredConstructors();
//5 获取运行时类的父类
clazz.getSuperclass();
//6 获取带泛型的父类
Type genericSuperclass = clazz.getGenericSuperclass();
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
//获取泛型类型
parameterizedType.getActualTypeArguments();
//7.获取运行时类实现的接口
clazz.getInterfaces();
//8.获取运行时类所在的包
clazz.getPackage();
//9.获取运行时类声明的注解
clazz.getAnnotations();
/**
* 调用运行时类中指定的结构:属性、方法、构造器
*/
//1 获取指定的属性,要求声明为public
Field age = clazz.getField("age");
//设置属性值
age.set(person, 1);
//获取属性值
int personAge = age.getInt(person);
//获取私有的属性
Field pvAge = clazz.getDeclaredField("age");
//设置该属性才能修改
pvAge.setAccessible(true);
pvAge.set(person, 1);
pvAge.get(person);
//2 操作指定的方法
Method setName = clazz.getDeclaredMethod("setName",String.class);
setName.setAccessible(true);
setName.invoke(person, "张三");
//调用静态方法
Method show = clazz.getDeclaredMethod("show");
show.setAccessible(true);
show.invoke(clazz);
//操作指定的构造器
Constructor constructor= clazz.getDeclaredConstructor(String.class);
constructor.setAccessible(true);
constructor.newInstance("张三");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}