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