`

Java注释(Annotation)

阅读更多
Java5中提供了新的注释(Annotation),能够为类提供额外信息,本文介绍了如何定义注释、如何使用注释和如何解析注释。
1、定义注释

package ch5;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// 注释什么时候起作用包括两种:RetentionPolicy.RUNTIME(编译并且在运行的时候可以找到),
// RetentionPolicy.SOURCE(编译的时候将被忽略)
@Retention(RetentionPolicy.RUNTIME)
// Target指出注释使用的地方:类或者接口上(ElementType.TYPE),
// 方法上(ElementType.METHOD),
// 属性上(ElementType.FIELD)
@Target({ElementType.TYPE})
public @interface Table {
 String name();
}

2、使用注释

package ch5;

@Table(name = "user")
public class UserBean {
 private String id;
 private String name;
}

3、解析注释

package ch5;

import java.lang.annotation.Annotation;

public class UserManger {
 private UserBean user;
 public static void main(String[] args) {
  System.out.println(new UserManger().getTable());
 }
 
 /*
  * 获取注释信息
  */
 public String getTable(){
  // 得到所有注释
  Annotation[] annotations = UserBean.class.getAnnotations();
  // 遍历
  for(Annotation annotation:annotations){
   // 看看是否有特定的注释
   if(annotation instanceof Table){
    return ((Table) annotation).name();
   }
  }
  return null;
 }
}

李绪成 CSDN Blog:http://blog.csdn.net/javaeeteacher
CSDN学生大本营:http://student.csdn.net/space.php?uid=124362
如果喜欢我的文章,就加我为好友:http://student.csdn.net/invite.php?u=124362&c=7be8ba2b6f3b6cc5
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics