一:
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);
}
}
}
}