测试,反射,注解1.junit测试1.1流程
1.2扩展的注解
2.反射2.1获取字节码文件的三种方式
2.2class功能
* Field[] getFields() :获取所有public修饰的成员变量 * Field getField(String name) 获取指定名称的 public修饰的成员变量 * Field[] getDeclaredFields() 获取所有的成员变量,不考虑修饰符 * Field getDeclaredField(String name)
* Constructor<?>[] getConstructors() * Constructor getConstructor(类<?>… parameterTypes) * Constructor getDeclaredConstructor(类<?>… parameterTypes) * Constructor<?>[] getDeclaredConstructors()
* Method[] getMethods() * Method getMethod(String name, 类<?>… parameterTypes) * Method[] getDeclaredMethods() * Method getDeclaredMethod(String name, 类<?>… parameterTypes)
* String getName() 2.3获取file方法获取该类的成员变量方法
2.4获取ConstructorConstructor:构造方法 获取构造方法们
* 如果使用空参数构造方法创建对象,操作可以简化:Class对象的newInstance方法 2.5获取Method
* Method[] getMethods() * Method[] getDeclaredMethods()
3.注解jdk1.5之后新特性,说明程序的 作用分类:
3.1自定义注解属性:接口中的抽象方法
元注解 public @interface 注解名称{ 属性列表; } * 本质:注解本质上就是一个接口,该接口默认继承Annotation接口 * public interface MyAnno extends java.lang.annotation.Annotation {} 补充1.@Retention: 定义注解的保留策略 @Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含 @Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得, @Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到 首 先要明确生命周期长度 SOURCE < CLASS < RUNTIME ,所以前者能作用的地方后者一定也能作用。一般如果需要在运行时去动态获取注解信息,那只能用 RUNTIME 注解;如果要在编译时进行一些预处理操作,比如生成一些辅助代码(如 ButterKnife),就用 CLASS注解;如果只是做一些检查性的操作,比如 @Override 和 @SuppressWarnings,则可选用 SOURCE 注解。 2.@Target:定义注解的作用目标 源码为: @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Target { ElementType[] value(); } @Target(ElementType.TYPE) //接口、类、枚举、注解 @Target(ElementType.FIELD) //字段、枚举的常量 @Target(ElementType.METHOD) //方法 @Target(ElementType.PARAMETER) //方法参数 @Target(ElementType.CONSTRUCTOR) //构造函数 @Target(ElementType.LOCAL_VARIABLE)//局部变量 @Target(ElementType.ANNOTATION_TYPE)//注解 @Target(ElementType.PACKAGE) ///包 3.@Document:说明该注解将被包含在javadoc中 4.@Inherited:说明子类可以继承父类中的该注解 3.2注解解析在程序使用(解析)注解:获取注解中定义的属性值 1. 获取注解定义的位置的对象 (Class,Method,Field) 2. 获取指定的注解 * getAnnotation(Class) //其实就是在内存中生成了一个该注解接口的子类实现对象 public class ProImpl implements Pro{ public String className(){ return “cn.itcast.annotation.Demo1”; } public String methodName(){ return “show”; } } 3. 调用注解中的抽象方法获取配置的属性值 来源:https://www./content-4-660301.html |
|