Java注解

这个东西老是忘记,做个笔记吧。

1.用途。

2.注解本质。

3.注解的使用。

1.用途

这是全部注解都继承的一个接口,Annotation。jdk1.8对其的说明是:所有注释类型扩展的公共接口。

其实可以就是为了能够在一边写代码一边在代码上写注释,这个注释可以为后面所用!

2.注解本质

public @interface Lable {

    String name="Lable";

    int getAge();

}

编译之后的class 文件再进行反编译,得到的就是如下:

public interface com.xx.Lable extends java.lang.annotation.Annotation {
  public static final java.lang.String name;
  public abstract int getAge();
}

所以注解的本质就是接口,但是最好在使用的时候尽量把它和接口分开,毕竟我们不是java的作者,而是使用者,因为注解里面的返回类型是做了限制的!

3.注解的使用

jdk1.5提供了4个元注解(指定放在注解上的)

1.@Target, 指定目标
2.@Retention, 注解保存到啥时候
3.@Documented, 是否在生成文档的时候保留
4.@Inherited 子类是否继承父类的注解(注解的继承性)

jdk1.8里面还添加了几个元注解!有兴趣可以去看看!

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

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

public @interface Lable {

    String name="Lable";

    int getAge();

}
@Lable(getAge = 1)
public class Person {

    private String name;

    public String getName(){
        System.out.println("Person");
        return "Person";
    }

} 
package com.xiu.annotation;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class main {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class<Person> cls=Person.class;
        Lable lable=cls.getAnnotation(Lable.class);
        int age=lable.getAge();
        String name=lable.name;
        System.out.println(name+':'+age);
    }
} 

通过 正在运行的Java应用程序中的类和接口 Class 对象(字节码对象)获取其字节码对象中的指定的注解对象(这里会动态的生成注解-接口-对象)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值