##自定义的注解有四个注意的内容:
* Target
@Target(ElementType.TYPE) // 注解可以使用的位置
* Retention
@Retention(RetentionPolicy.RUNTIME)// 生命周期
* Documented
@Documented
// 其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。
* Inherited
@Inherited// 可以被子类继承
示例代码:
Table.java
@Target(ElementType.TYPE)
// 注解可以使用的位置
@Retention(RetentionPolicy.RUNTIME)
// 生命周期
@Documented
// 其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。
@Inherited
// 可以被子类继承
public @interface Table {
String value();
}
Column.java
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
String value();
}
实体类
person.java
@Table("person")
public class Person {
@Column("id")
private int id;
@Column("name")
private String name;
@Column("age")
private int age;
@Column("email")
private String email;
//get/set...
}
测试类
public static void main(String[] args) {
query(new Person());
}
public static String query(Object o) {
boolean b = o.getClass().isAnnotationPresent(Table.class);
if (!b) {
return null;
}
Table table = o.getClass().getAnnotation(Table.class);
String tableName = table.value();
System.out.println("tableName>>" + tableName);// 获取table表名
Field[] fields = o.getClass().getDeclaredFields();
for (Field f : fields) {
boolean feildIsAnnotationed = f.isAnnotationPresent(Column.class);
if (!feildIsAnnotationed) {
continue;
}
Column c = f.getAnnotation(Column.class);
System.out.println("列注解的值:" + c.value());// 获取注解的列名
String fieldName = f.getName();
System.out.println("列名:" + fieldName);
// 通过反射获取列的值
String getMethod = "get" + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
System.out.println("方法名:" + getMethod);
try {
Method method = o.getClass().getMethod(getMethod);
System.out.println("方法的返回值》》》" + method.invoke(o));
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
浙公网安备 33010602011771号