注解

一:

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);


        }
    }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值