新闻正文

侵入,无侵入? Annotation vs Interface

来源:JAVA天堂  JAVA学习者  2007-4-25 04:13:25 网友评论 0 条 字体:[ ] ~我要投稿!

 

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() 这个函数在编译期也检查不出来。



收藏到ViVi   收藏此页到365Key
上一篇:spring+hibernate+jbpm整合成功
下一篇:Jpetstore阅读心得之分层结构
用户名:新注册) 密码: 匿名评论 [所有评论]
评论内容:不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
Copyright 2003-2008 www.javah.net All Rights Reserved
2008 如果你喜欢本站 请收藏本站 并推荐给你的朋友一起分享