java复习

2020-08-10注解

2020-08-16  本文已影响0人  智障猿

概念

JDK中预定义的注解

注解 说明
@Override 检测被该注解标注的方法是否继承自父类(接口)的
@Deprecated 该注解标注的内容,标识已过时
@Suppreswarnings("all") 压制警告

自定义注解

ElementType的取值

取值 说明
Type 可以作用于类上
METHOD 可以作用于方法上
FIELD 可以作用于变量上

RetentionPolicy的取值

取值 说明
SOURCE 注解只保留在源文件,当Java文件编译成class文件的时候,注解被遗弃
CLASS 当前被描述的注解,会保留到class字节码文件中,但jvm加载class文件时候被遗弃
RUNTIME 当前被描述的注解,会保留到class字节码文件中,并被JVM读取到

使用(解析)注解

  1. 获取注解定义的位置的对象(反射Class,Method,Field)
  2. 获取指定的注解(对象.getAnnotation(注解名.class))
  3. 调用注解中的抽象方法获取配置的属性值
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Pro {
    String className();
    String method();
}


import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Pro(className = "cn.it.Student",method = "study")
public class Test {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//        1.解析注解
//        1.1获取该类的字节码文件对象
        Class<?> aClass = Class.forName("cn.it.Test");
//        2.获取注解对象
        //其实就是在内存中生成了一个该注解接口的子类实现对象
        /*
        public class ProImpl implement Pro{
            public String className(){
                return “cn.it.Student”;
            }
            public String method(){
                return "study";
            }
        }
         */
        Pro annotation = aClass.getAnnotation(Pro.class);
//        3.调用注解对象中定义的抽象方法,获取返回值
        String className = annotation.className();
        String method = annotation.method();
//        4.加载指定的类到内存
        Class<?> aClass1 = Class.forName(className);
        Constructor<?> constructor = aClass1.getConstructor();
//        5.创建对象
        Object o = constructor.newInstance();
//        6.获得指定方法对象
        Method method1 = aClass1.getMethod(method);
//        7.执行方法
        method1.invoke(o);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读