自定义注解

public class Demo01 {
   //注解可以显示赋值,如果没有默认值,我们就必须给注解赋值
    @MyAnnotation(age=17)  //有参数名并布赋值
    public void test(){}
}

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
    //注解的参数格式:  参数类型 参数名()
    String name() default "";
    int age();
    int id() default -1; //如果默认值为1,代表不存在

    String[] school() default {"清华大学","北京大学"};
}
public class Demo02 {
   //注解可以显示赋值,如果没有默认值,我们就必须给注解赋值
    @MyAnnotation2("你好,世界")  //没有参数名直接赋值
    public void Test2(){}
}

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)

//不成文的规定,如果注解中参数只有一个,那么建议使用value命名,在调用时可以不写参数名,直接赋值
@interface MyAnnotation2{
    String value();
}

注解的本质其实是一个接口,只是继承了注解类。

自定义注解(源文件)

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

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String name() default  "张三";
    int age();
}

反编译后的注解(.class文件编译后的注解)



import java.lang.annotation.Annotation;

public interface MyAnnotation
	extends Annotation
{

	public abstract String name();

	public abstract int age();
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值