练习

image.png
代码实现

  1. public class Test12 {
  2. @Test
  3. public void test02() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
  4. Class c1 = Class.forName("com.demo03.Student");
  5. Student student = (Student) c1.newInstance();
  6. Method setName = c1.getDeclaredMethod("setName", String.class);
  7. // invoke方法 激活方法 (对象,和参数值)
  8. setName.invoke(student,"xiaoli");
  9. System.out.println(student.getName());
  10. System.out.println(student.toString());
  11. }
  12. public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
  13. Class c1 = Class.forName("com.demo03.Student");
  14. // 通过反射获得注解
  15. Annotation[] annotations = c1.getAnnotations();
  16. for (Annotation annotation : annotations) {
  17. System.out.println(annotation);
  18. }
  19. // 通过类对象获取指定注解 ,并获得指定注解的值
  20. Table table = (Table)c1.getAnnotation(Table.class);
  21. String value = table.value();
  22. System.out.println(value);
  23. // 获得类指定的注解
  24. java.lang.reflect.Field name = c1.getDeclaredField("name");
  25. Field annotation = name.getAnnotation(Field.class);
  26. System.out.println(annotation.columnName());
  27. }
  28. }
  29. @Table("db_student")
  30. class Student{
  31. @Field(columnName = "db_id",type = "int",length = 10)
  32. private int id;
  33. @Field(columnName = "db_age",type = "int",length = 10)
  34. private int age;
  35. @Field(columnName = "db_name",type = "varchar",length = 10)
  36. private String name;
  37. public Student(){
  38. }
  39. public Student(int id, int age, String name) {
  40. this.id = id;
  41. this.age = age;
  42. this.name = name;
  43. }
  44. public int getId() {
  45. return id;
  46. }
  47. public void setId(int id) {
  48. this.id = id;
  49. }
  50. public int getAge() {
  51. return age;
  52. }
  53. public void setAge(int age) {
  54. this.age = age;
  55. }
  56. public String getName() {
  57. return name;
  58. }
  59. public void setName(String name) {
  60. this.name = name;
  61. }
  62. @Override
  63. public String toString() {
  64. return "Student{" +
  65. "id=" + id +
  66. ", age=" + age +
  67. ", name='" + name + '\'' +
  68. '}';
  69. }
  70. }
  71. //创建一个名为Table的注解
  72. //使用元注解 定义注解的作用域
  73. //代表类名注解 和运行时起作用
  74. @Target(ElementType.TYPE)
  75. @Retention(RetentionPolicy.RUNTIME)
  76. @interface Table{
  77. // 注解参数形式 参数类型 +参数名+()
  78. String value();
  79. }
  80. //属性的注解
  81. @Target(ElementType.FIELD)
  82. @Retention(RetentionPolicy.RUNTIME)
  83. @interface Field{
  84. String columnName();
  85. String type();
  86. int length();
  87. }