instanceof UndeletableEntity{
((UldeletableEntity)bean).setStatus("-1");
}
侵入,无侵入? Annotation vs Interface
来源:互联网
作者:west263.com
时间:2008-02-23
点击:
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!
大家都很熟悉的写法,就不解释了。
Annotation是这样实现的:
Annotation 定义:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Undeletable {
String status() default "status";
}
@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;
}
}
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();
}
Undeletable anno = (Undeletable) entityClass.getAnnotation(Undeletable.class);
statusProperty = anno.status();
}
可见,annotation的模式,比interface要少一点侵入性,不定死status列的名称,而且还可以灵活定义更多元属性,比如定义无效时的值为"-1","unvalid"。
但是,这种模式也和所有动态的东西向一样,失去了编译期校验的优势,POJO如果没有setStatus() 这个函数在编译期也检查不出来。
上一篇: 关于java数组的深度思考
下一篇: 自我参考:Java学习的30个目标
文章整理:西部数码--专业提供域名注册、虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!


