Interface是这样实现的:
Interface 定义:
public interface UndeletableEntity {
void setStatus(String status);
}
Interface 在Entity使用:
public class Book implements UndeletableEntity {
private String status; public void setStatus(String status) {
this.status = status;
}
}
Interface 在框架中使用:
//根据Class 判断
if(UndeletableEntity.class.isAssignableFrom(entityClass)){
...
}
//根据Bean实体判断
if(bean instanceof UndeletableEntity{
((UldeletableEntity)bean).setStatus("-1");
}
大家都很熟悉的写法,就不解释了。
Annotation是这样实现的:
Annotation 定义:
@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() 这个函数在编译期也检查不出来。
查看本文来源