注解:不会干扰(影响)主程序的正常运行
标注注解 @Override(空注解 编译检查)单值注解 @Test(id=1)
完整注解(多值注解) @Test(id=1,text="lalala")
@Deprecated 过时方法注解
@Override 编译检查注解
@suppressWarning 警告注解
@suppressWarning("all") 把警告消除(强迫症的救星)
自定义注解 格式
@限制xxxpublic @interface TestAnnotation
使用
@TestAnnotation修饰 放到要修饰的方法
@retention
保留策略
@retention(value=RetentionPolicy.RUNTIME )RetentionPolicy.source 源文件注解
RetentionPolicy.CLASS 编译时注解
RetentionPolicy.RUNTIME 运行时注解(要使用反射必须使用这个)
@Target(元注解) 表示限制修饰的程序元素的类型
@Target(value=ElemnetType.Method)修饰方法
METHOD修饰方法 FIELD修饰属性
TYPE修饰类或接口 PARAMS修饰参数
返回值(基本类型+Clas枚举 String注解类型)以及他们的一维数组
自定义注解注意
1.方法里必须有返回类型2.方法里不允许有参数
特殊情况
1.可以用default关键字赋默认值2.可以使用value作为元素名称,可以省略value
自定义
@Target(value={ElemnetType.Method,ElemnetType.FIELD
ElemnetType.TYPE,ElemnetType.PARAMS})
//这个用在类名上面即和 ElemnetType.TYPE配合使用
@retention(value=RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
int test() default 0(default赋默认值);
String value;
String text();
Color color();
String[] names();
}
使用
@TestAnnotation(test=1234,text="哈哈",
=Color.RED,name={"1234","123","1"})
@override
public String toString() {return "你好"}
注解配合反射使用 简化配置
反射获取类名上的注解
User user=new User();
Class<> cls=user.getClass();
TestAnnotation annotation=cls.getAnnotation(TestAnnotation.class)
if(annotation!=null){
int id=annotation.id();
String name=annotation.text()...}
反射获取类里面属性(方法)注解
cls.getDeclaredFields()
cls.getDeclaredMethods()
/**
* Servlet 3.0之后支持注解配置
* 采用注解方式注册 就不要在web.xml注册
*///@WebServlet({"account/login" ,"account/login1" ,"account/login2"})
@WebServlet(value = "/account/login", initParams = {
@WebInitParam(name = "charset", value = "UTF-8"),
@WebInitParam(name = "charset", value = "UTF-8")
},
loadOnStartup = 1)
//@WebServlet("/account/login")