具体使用

  1. try {
  2. Class clazz =Class.forName("test.Person");
  3. //1 创建对象
  4. Person person = (Person)clazz.newInstance();
  5. //2 获取属性对象,获取运行时类和所有父类中public的属性
  6. Field[] fields = clazz.getFields();
  7. //运行时类中的所有属性(不含父类)
  8. Field[] fields1 = clazz.getDeclaredFields();
  9. for(Field field:fields1){
  10. //权限修饰符
  11. Modifier.toString(field.getModifiers());
  12. //类型
  13. field.getType();
  14. //变量名
  15. field.getName();
  16. }
  17. //3 获取运行时类及其父类中所有public的方法
  18. Method[] methods = clazz.getMethods();
  19. //运行时类中的所有方法(不含父类)
  20. Method[] methods1 = clazz.getDeclaredMethods();
  21. for(Method method:methods){
  22. //获取方法生成的注解(元注解Retention声明为RUNTIME才能获取到)
  23. method.getAnnotations();
  24. //权限修饰符
  25. Modifier.toString(method.getModifiers());
  26. //返回值类型
  27. method.getReturnType().getName();
  28. //方法名称
  29. method.getName();
  30. //获取形参列表
  31. Class[] parameterTypes = method.getParameterTypes();
  32. for(Class parameterType:parameterTypes){
  33. parameterType.getName();
  34. }
  35. //抛出的异常
  36. Class[] exceptionTypes = method.getExceptionTypes();
  37. for(Class exceptionType:exceptionTypes){
  38. exceptionType.getName();
  39. }
  40. }
  41. //4 获取当前运行时类声明为public的构造器
  42. Constructor[] constructors= clazz.getConstructors();
  43. //获取当前运行时类所有的构造器
  44. clazz.getDeclaredConstructors();
  45. //5 获取运行时类的父类
  46. clazz.getSuperclass();
  47. //6 获取带泛型的父类
  48. Type genericSuperclass = clazz.getGenericSuperclass();
  49. ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
  50. //获取泛型类型
  51. parameterizedType.getActualTypeArguments();
  52. //7.获取运行时类实现的接口
  53. clazz.getInterfaces();
  54. //8.获取运行时类所在的包
  55. clazz.getPackage();
  56. //9.获取运行时类声明的注解
  57. clazz.getAnnotations();
  58. /**
  59. * 调用运行时类中指定的结构:属性、方法、构造器
  60. */
  61. //1 获取指定的属性,要求声明为public
  62. Field age = clazz.getField("age");
  63. //设置属性值
  64. age.set(person, 1);
  65. //获取属性值
  66. int personAge = age.getInt(person);
  67. //获取私有的属性
  68. Field pvAge = clazz.getDeclaredField("age");
  69. //设置该属性才能修改
  70. pvAge.setAccessible(true);
  71. pvAge.set(person, 1);
  72. pvAge.get(person);
  73. //2 操作指定的方法
  74. Method setName = clazz.getDeclaredMethod("setName",String.class);
  75. setName.setAccessible(true);
  76. setName.invoke(person, "张三");
  77. //调用静态方法
  78. Method show = clazz.getDeclaredMethod("show");
  79. show.setAccessible(true);
  80. show.invoke(clazz);
  81. //操作指定的构造器
  82. Constructor constructor= clazz.getDeclaredConstructor(String.class);
  83. constructor.setAccessible(true);
  84. constructor.newInstance("张三");
  85. } catch (Exception e) {
  86. // TODO Auto-generated catch block
  87. e.printStackTrace();
  88. }