@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Undeletable {
String status() default "status";
} 原本怪Sun怎么这么抠门,用@interface 而不另外搞一个关键字,原来Sun的意思就是把Interface和Annotation的定位一样呀。
@Target 定义Annotation 可用于的地方,比如类型,函数,函数参数等。Type代表Class,Interface...
@Retention(RetentionPolicy.RUNTIME)表明是个运行期的annotation,否则后面的代码都不会起作用。
String status() 定义了annotation有个status的属性,而且可以不定义,默认为status。
Annotation在Entity使用:
@Undeletable
public class Book{
private String status;
public void setStatus(String status) {
this.status = status;
}
}
@Undeletable(status = "status2")
public class BookWithNewStatus {
private String status2;
public void setStatus2(String status2) {
this.status2 = status2;
}
}Annotation在框架中的使用:
if (entityClass.isAnnotationPresent(Undeletable.class)) {
Undeletable anno = (Undeletable) entityClass.getAnnotation(Undeletable.class);
statusProperty = anno.status();
} 可见,annotation的模式,比interface要少一点侵入性,不定死status列的名称,而且还可以灵活定义更多元属性,比如定义无效时的值为"-1","unvalid"。
但是,这种模式也和所有动态的东西向一样,失去了编译期校验的优势,POJO如果没有setStatus() 这个函数在编译期也检查不出来。
收藏到ViVi 收藏此页到365Key
上一篇:
spring+hibernate+jbpm整合成功 下一篇:
Jpetstore阅读心得之分层结构