注解相當(dāng)于一種標(biāo)記势告,在程序中加了注解就等于為程序打上了某種標(biāo)記啦逆。程序可以利用java的反射機(jī)制來了解你的類及各種元素上有無何種標(biāo)記百姓,針對(duì)不同的標(biāo)記,就去做相應(yīng)的事件瓢阴。
基本注解
- @Override 重寫
- @Deprecated過時(shí)
- @SuppressWarnings壓縮警告(可以無視一些警告)
元注解
元注解:用來描述注解的注解
- @Retention--該注解什么時(shí)候生效
- @Target--該注解用在哪里
- @Documented
- @Inherited
- @Repeatable (java 8新增)
具體使用
//注解的定義
package com.annotation;
@Retention(RUNTIME)//runtime指的是運(yùn)行時(shí)生效畅蹂,還有class,document
@Target({FIELD,METHOD})//用在變量和方法上荣恐,當(dāng)有多個(gè)的時(shí)候用{數(shù)組}
public @interface wuli {
String value();
}
//用注解
package com.annotation;
public class User {
@wuli("JAX")//當(dāng)注解里面的只有一個(gè)value的時(shí)候可以不寫value="JAX"
private String username;
}
//用反射的方法讀取注解里的信息
package com.annotation;
import java.lang.reflect.Field;
public class TestAnnotation {
public static void main(String[] args) throws NoSuchFieldException, SecurityException {
User user=new User();
Field field=user.getClass().getDeclaredField("username");
wuli annotation=field.getAnnotation(wuli.class);
System.err.println(annotation.value());
}
}