一:
package com.zhujie;
@MyAnnotation(name=”XB”,like={“睡覺”,”吃飯”},sex=EnumSex.GG)
public class User {
private String name;
//@Overrid:方法的重寫(系統自定義的註解)
@Override
public String toString() {
return "User [name=" + name + "]";
}
//@Deprecated:系統自定義的註解,已經過時的標記
@Deprecated
public void print(){
System.out.println("name=" + name);
}
public User(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
//註解用於方法的參數
public void setName(@MyAnnotation(name="XB",like={"吃飯","睡覺"},sex=EnumSex.GG) String name) {
this.name = name;
}
}
二:
package com.zhujie;
public enum EnumSex {
MM,GG
}
三:自定義註解
package com.zhujie;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定義一個註解
* @author Administrator
* 三個系統註解:@Deprecated,@Override,@SuppressWarnings(“deprecation”)
* 四個元註解:@Documented ,@Target,@Inherited,@Retention
*
*/
@Documented//文檔註釋:也是元註解
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.PARAMETER})//表示註解的使用範圍
@Inherited//是否允許被子類繼承下來
//對註解的註解叫元註解:@Retention(value=RetentionPolicy.RUNTIME):作用範圍爲:運行時
@Retention(value=RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
//定義一個屬性
public String name();
//給屬性指定默認值
public String info() default "WSDR";
//定義一個數組變量
public String[] like();
//定義一個枚舉變量
public EnumSex sex();
}
AnnotationDemo
package com.zhujie;
import java.lang.annotation.Annotation;
public class AnnotationDemo {
//@SuppressWarnings(“deprecation”):忽略過時的警告
@SuppressWarnings(“deprecation”)
public static void main(String[] args) throws Exception {
User user = new User(“XB”);
user.print();
//使用反射解析註解
Class<?> c = Class.forName("com.zhujie.User");
//獲取當前類標記的所有註解
Annotation[] annotations = c.getAnnotations();
System.out.println(annotations.length);
//循環遍歷所有的註解
for (Annotation a : annotations) {
//判斷是否是指定的註解
if (c.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation ma = (MyAnnotation)a;
String name = ma.name();
System.out.println(name);
}
}
}
}