1.注解的好处
1.采用纯java代码,不在需要配置繁杂的xml文件
2.在配置中也可享受面向对象带来的好处
3.类型安全对重构可以提供良好的支持
4.减少复杂配置文件的同时亦能享受到springIoC容器提供的功能
2.什么是注解
对程序进行标注和解释的东西
3.java中的一些注解及其作用
注解 | 作用 |
---|---|
@Override | 表示子类重写父类方法 |
@Deprecated | 表示过时的,用该注解的东西标记会加个横线 |
@SuppressWarnings(value = "all") | 压制警告 |
4.注解的分类
普通注解、元注解、自定义注解。
5.自定义注解
1.格式
public @interface A {
//权限修饰符只能是public可以省略 类型 属性 () default 默认值;
//基本数据类型
int a () default 1;
//String
public String b();
//Class
Class c () default Test.class;
//注解
B d () default @B;
//枚举类型
Season e () default Season.DONG;
//以上类型的一维数组
int[] f () default {1,2,3};
Season[] g () default {Season.DONG,Season.QIU};
}
2.属性的类型
基本数据类型、String、Class、注解、枚举类型以及以上类型的一维数组
3.使用
有默认值的可以不用赋值,没有的必须手动赋值,不然报错
@A(b = "10")
public static void method(){
int a = 0;
//System.out.println(a);
}
6.特殊的属性value
若只有value需要赋值,则可以省略属性名,直接赋值
A(value = 1)
public static void method(){
int a = 0;
//System.out.println(a);
}
@A(1)
public static void method(){
int a = 0;
//System.out.println(a);
}
public @interface A {
//权限修饰符只能是public可以省略 类型 属性 () default 默认值;
//基本数据类型
int a () default 1;
//String
public String b() default "1";
//Class
Class c () default Test.class;
//注解
B d () default @B;
//枚举类型
Season e () default Season.DONG;
//以上类型的一维数组
int[] f () default {1,2,3};
Season[] g () default {Season.DONG,Season.QIU};
int value() ;
}
7.自定义注解的练习
自定义@Test注解,类中被该注解标注的方法才会被执行
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
}
public class TestClass {
@Test
public void method1(){
System.out.println("method1");
}
public void method2(){
System.out.println("method2");
}
public void method3(){
System.out.println("method3");
}
@Test
public void method4(){
System.out.println("method4");
}
}
public class Main {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
//1.获得class对象
Class clazz = Class.forName("annotation.TestClass");
TestClass ts = (TestClass) clazz.newInstance();
//2.反射得到所有方法
Method[] declaredMethods = clazz.getDeclaredMethods();
//3.遍历所有方法,判断是否被@Test注解修饰
for (Method method : declaredMethods) {
//isAnnotationPresent(类<? extends Annotation> annotationClass)
if(method.isAnnotationPresent(Test.class)== true){
//存在该注解
method.invoke(ts);
}
}
}
}
8.元注解
描述注解的注解
元注解 | 作用 |
---|---|
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD}) | 指定注解的作用位置 |
@Retention(RetentionPolicy.RUNTIME) | 指定注解的存活时间 |
@Inherited | 表示子类可以继承父类的注解 |
@Documented | 表示该注解会出现在API文档 |
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Test {
}
@Test
public class People {
}
public class Student extends People{
}
public class Test01 {
public static void main(String[] args) throws Exception {
//1.获取字节码对象
Class clazz = Class.forName("annotation.Student");
//2.判断类上是否存在注解
boolean anonymousClass = clazz.isAnnotationPresent(Test.class);
//3.true表示子类继承到了父类的@Test注解
System.out.println(anonymousClass);
}
}