练习

代码实现
public class Test12 {@Testpublic void test02() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {Class c1 = Class.forName("com.demo03.Student");Student student = (Student) c1.newInstance();Method setName = c1.getDeclaredMethod("setName", String.class);// invoke方法 激活方法 (对象,和参数值)setName.invoke(student,"xiaoli");System.out.println(student.getName());System.out.println(student.toString());}public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {Class c1 = Class.forName("com.demo03.Student");// 通过反射获得注解Annotation[] annotations = c1.getAnnotations();for (Annotation annotation : annotations) {System.out.println(annotation);}// 通过类对象获取指定注解 ,并获得指定注解的值Table table = (Table)c1.getAnnotation(Table.class);String value = table.value();System.out.println(value);// 获得类指定的注解java.lang.reflect.Field name = c1.getDeclaredField("name");Field annotation = name.getAnnotation(Field.class);System.out.println(annotation.columnName());}}@Table("db_student")class Student{@Field(columnName = "db_id",type = "int",length = 10)private int id;@Field(columnName = "db_age",type = "int",length = 10)private int age;@Field(columnName = "db_name",type = "varchar",length = 10)private String name;public Student(){}public Student(int id, int age, String name) {this.id = id;this.age = age;this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Student{" +"id=" + id +", age=" + age +", name='" + name + '\'' +'}';}}//创建一个名为Table的注解//使用元注解 定义注解的作用域//代表类名注解 和运行时起作用@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@interface Table{// 注解参数形式 参数类型 +参数名+()String value();}//属性的注解@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)@interface Field{String columnName();String type();int length();}
