java注解和反射例子
package com.wang.test01; import java.lang.annotation.*; import java.lang.reflect.Field; //反射和注解 public class test { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { Class c1= Class.forName("com.wang.test01.User"); //通过反射获得注解 Annotation[] annotations = c1.getAnnotations(); for (Annotation annotation : annotations) { System.out.println(annotation); } Table Tableannotation = (Table) c1.getAnnotation(Table.class); String value = Tableannotation.value(); System.out.println(value); //获得类指定的注解 Field f = c1.getDeclaredField("name"); Fieldwang fAnnotation = f.getAnnotation(Fieldwang.class); System.out.println(fAnnotation.columnName()); System.out.println(fAnnotation.type()); System.out.println(fAnnotation.length()); } } //实体类 @Table("学生") class User{ @Fieldwang(columnName = "db_name",type = "int",length = 10) private String name; @Fieldwang(columnName = "db_id",type = "int",length = 10) private int id; @Fieldwang(columnName = "db_age",type = "int",length = 10) private int age; public User() { } public User(String name, int id, int age) { this.name = name; this.id = id; this.age = age; } public String getName() { return name; } public void setName(String name) { 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; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", id=" + id + ", age=" + age + '}'; } } @Target(ElementType.TYPE) //只允许注解类 @Retention(RetentionPolicy.RUNTIME) @interface Table { String value(); } @Target(ElementType.FIELD) //只允许属性注解 @Retention(RetentionPolicy.RUNTIME) @interface Fieldwang{ String columnName(); String type(); int length(); }