java注解学习笔记

注解概述

注解就是代码中的特殊标记, 用于替代配置文件.
相比配置文件而言(比如.xml, .properties等), 语义化更好, 看起来直观, 类型也可以直接获取,
不像在配置文件中, 读到的都是字符串, 还要做各种转换.

三个常用的注解

@Override, @SuppressWarnings, @Deprecated
例子:

public class ComponentClass {

    // overwrite父类中的方法
    @Override
    public boolean equals(Object obj) {
        return super.equals(obj);
    }

    // 标注为已过时, 不建议再使用
    @Deprecated
    public void oldMethod() {

        // 抑制警告
        @SuppressWarnings("unused")
        int i = 0;
    }
}

编写自己的注解

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

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
public @interface Component {

    String selector() default "app";
    String template();

    ChildComponent c() default @ChildComponent(selector="c-app", template="<div></div>");
}

注解的属性

注解的属性可以有以下一些类型:
原始数据类型(boolean, byte, char, short, int, long, float, double), 字符串,
类, 注解(比如上面的ChildComponent), 枚举或者上述类型的一维数组.

元注解(meta annotation)

常用的元注解: @Retention, @Target.

@Retention: 注解保留的时期(域, scope), 有三个值:

时期说明注意事项
RetentionPolicy.SOURCE编译过后就丢弃, 在字节码中已经没有了
RetentionPolicy.CLASS注解可以保留在java字节码中,jvm运行时不会保留该注解默认值
RetentionPolicy.RUNTIME注解可以保留在运行期, 可以通过反射获取常用

@Target: 注解可以作用到的位置: 可取的值有: 类, 接口, 枚举, 注解, 字段(包括枚举常量), 方法声明,
形式参数, 构造函数声 局部变量, 包, 类型参数(1.8新加), 类型声明(1.8新加).

解析注解

主要是利用反射相关的方法来解析, 如:

import java.lang.reflect.Method;

public class ComponentClass {

    @Component(selector="app", template="<div>component</div>",
            c=@ChildComponent(selector="c-app", template="<div>child</div>"))
    public Component parseAnnotation() {
        Method method;
        try {
            method = ComponentClass.class.getMethod("parseAnnotation", new Class[]{});
            Component c = method.getAnnotation(Component.class);
            return c;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 测试代码
    public static void main(String[] args) {
        ComponentClass cc = new ComponentClass();
        Component c = cc.parseAnnotation();
        /*输出:
        selector: app, template: <div>component</div>,
        c.selector: c-app, c.template: <div>child</div>
        */
        System.out.printf("selector: %s, template: %s,\nc.selector: %s, c.template: %s",
                c.selector(), c.template(), c.c().selector(), c.c().template());
    }
}

可以看到: c.selector, c.cc().selector这种语法还是很简洁的.

欢迎补充指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值