定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD) //*必填 ElemenetType.FIELD 属性/ElemenetType.METHOD 方法
@Retention(RetentionPolicy.RUNTIME) // *必填
public @interface AccessORMAnno
{
/**
* 数据库字段名
* @return
*/
public String dbField();
/**
* 是否是主键
* @return
*/
public boolean isPK() default false; //设置默认值 ,有默认值可以不填
/**
* 是否是主键
* @return
*/
public boolean isPK2() default false; //设置默认值 ,有默认值可以不填
}
注释使用
public class AnnotationTest
{
@AccessORMAnno (dbField ="id" ,isPK=true )
private int id;
@AccessORMAnno (dbField ="name" ,isPK2=false )
private String name;
}
测试
import java.lang.reflect.Field;
public class Test
{
public static void main(String[] args)
{
AnnotationTest t = new AnnotationTest();
Field[] arr = t.getClass().getDeclaredFields();
for (Field field : arr)
{
boolean hasAnnotation = field
.isAnnotationPresent(AccessORMAnno.class);
if (hasAnnotation)
{
AccessORMAnno anno = field.getAnnotation(AccessORMAnno.class);
System.out.println(anno.dbField() + " " + anno.isPK());
}
}
System.out.println("success");
}
}
运行结果
id true
name false
success