注解概述
注解就是代码中的特殊标记, 用于替代配置文件.
相比配置文件而言(比如.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
这种语法还是很简洁的.
欢迎补充指正!