JAVA-注解Annotation与反射Reflection
注解
概念
- Annotation是从JDK5.0开始引入的新技术
- Annotation的作用:
- 不是程序本身,可以对程序作出解释
- 可以被其他程序(如编译器)读取
- Annotation的格式:
"@注释名"
或"@注释名(参数值)"
- Annotation使用位置:
可以附加在package,class,method,field等等上面,相当于为其添加了额外的辅助信息,可以通过反射机制编程实现对这些元数据的访问
内置注解
@Override
:定义在java.lang.Override中,表示一个方法声明打算重写超类中的另一个方法声明@Deprecated
:定义在java.lang.Deprecated中,表示不鼓励程序员使用这样的元素@SuppressWarnings
:定义在java.lang.SuppressWarnings中,用来抑制编译时的警告信息,他需要添加一个参数才能正确使用,这些参数是已经定义好的参数,例如
- @SuppressWarnings(“all”)
- @SuppressWarnings(“unchecked”)
- …
元注解
元注解的作用就是负责注解其他注解,java定义了4个标准的meta-annotation类型,他们被用来提供对其他annotation类型作说明
package com.utils;import java.lang.annotation.*;public class TestAnnotation { @MyAnnotation public static void main(String[] args) { System.out.println("测试注解"); }}//Target 表示这个注解可以作用的地方@Target(value = {ElementType.TYPE,ElementType.METHOD})//Retention 表示我们的注解在什么地方起作用,runtime>class>sources@Retention(value = RetentionPolicy.RUNTIME)//Documented 表示是否将该注解生成在javaDoce中@Documented//Inherited 表示子类可以继承父类的注解@Inherited//定义一个注解使用@interface@interface MyAnnotation{}
自定义注解
使用
@interface
自定义注解时,自动继承了java.lang.annotation.Annotation
接口
package com.utils;import java.lang.annotation.*;public class TestAnnotation { @MyAnnotation public static void main(String[] args) { System.out.println("测试注解"); }}//Target 表示这个注解可以作用的地方@Target(value = {ElementType.TYPE,ElementType.METHOD})//Retention 表示我们的注解在什么地方起作用,runtime>class>sources@Retention(value = RetentionPolicy.RUNTIME)//Documented 表示是否将该注解生成在javaDoce中@Documented//Inherited 表示子类可以继承父类的注解@Inherited//定义一个注解使用@interface@interface MyAnnotation{ //注解的参数 : 参数类型 参数名(); String name() default ""; int age() default 0; int length() default -1;//如果默认值为-1,代表不存在}//只有一个参数@interface MyAnnotation2{ String value();}
反射机制
动态语言与静态语言
- 动态语言:
是一类在运行时可以改变其结构的语言:例如新的函数、对象、甚至代码可以被引进,已有的函数可以被删除或是其他结构上的变化,即在运行时代码可以根据某一些条件改变自身结构
主要的一些动态语言例如:C#、JavaScript、PHP、Python等- 静态语言:
即运行时结构不可变的语言,例如java、C、C++等等
Java虽然不是动态语言,但是Java具有一定的动态性,可以利用反射机制获得类似动态语言的特性,Java的动态性让编程的时候更加灵活!
反射
- Reflection(反射)是java被视为动态语言的关键,反射机制允许程序在执行期间借助于Reflection API取得任何类的内部消息,并能够直接操作任意对象的内部属性以及方法
- 加载玩类后,在堆内存的方法区就产生了一个Class类型的对象(一个类只有一个Class对象),这个对象包含了完整的类的结构信息,
反射优缺点
- 优点:可以实现动态创建爱你对象和编译,体现出很大的灵活性
- 缺点:对性能有影响,使用反射基本上是一种解释操作,我们可以告诉JVM,我们希望做什么并且它满足我们的要求,这类操作总是慢于 直接执行相同的操作。
Class类
获取Class实例
获取类的运行时结构
package com.utils;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;public class Test29 { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException { Class aClass = Class.forName("com.utils.Student"); //获得类的名字 System.out.println(aClass.getName());//包名+类名 System.out.println(aClass.getSimpleName());//类名 //获得类的属性 Field[] fields = aClass.getFields();//只能获取public属性 for (Field field : fields) { System.out.println(field); } System.out.println("--------"); Field[] fields2 = aClass.getDeclaredFields();//获得全部属性 for (Field field : fields2) { System.out.println(field); } //获得指定属性的值 Field age = aClass.getDeclaredField("age"); System.out.println(age); //获得类的方法 System.out.println("----------"); Method[] methods = aClass.getMethods();//获得本类及其父类全部public方法 for (Method method : methods) { System.out.println(method); } System.out.println("----------"); Method[] declaredMethods = aClass.getDeclaredMethods();//获得本类的所有方法 for (Method declaredMethod : declaredMethods) { System.out.println(declaredMethod); } System.out.println("-------------"); //获得指定方法 Method method = aClass.getMethod("getName",null); Method method1 = aClass.getMethod("setName",String.class); System.out.println("-------------"); //获得构造器 Constructor[] constructors = aClass.getConstructors(); for (Constructor constructor : constructors) { System.out.println(constructor); } Constructor[] declaredConstructors = aClass.getDeclaredConstructors(); for (Constructor constructor : declaredConstructors) { System.out.println(constructor); } //获得指定的构造器 Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class,String.class); System.out.println(declaredConstructor); }}
动态创建对象
package com.utils;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class Test30 { public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException { //获得Class对象 Class aClass = Class.forName("com.utils.Student"); //1.构造一个对象 Student o = (Student)aClass.newInstance();//本质是调用了类的无参构造器 //2.通过构造器创建对象 Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class, String.class); Student user = (Student) declaredConstructor.newInstance("cx", "12"); System.out.println(user); //通过反射调用方法 Method setName = aClass.getDeclaredMethod("setName", String.class); setName.invoke(user,"cxe"); System.out.println(user); //通过反射修改属性值 Field name = aClass.getDeclaredField("name"); name.setAccessible(true);//关掉权限检测,不然会报错,说私有属性不能访问 name.set(user,"cx"); System.out.println(user); }}
setAccessible对性能的影响
package com.utils;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class Test31 { public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { Test31 test31 = new Test31(); test31.t1(); test31.t2(); test31.t3(); } //普通方式调用 最快 public void t1(){ Student student = new Student(); long l = System.currentTimeMillis(); for (int i = 0; i < 1000000000; i++) { student.getName(); } long l1 = System.currentTimeMillis(); System.out.println(l1-l); } //反射方式 不关闭权限检测 最慢 public void t2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Student student = new Student(); Class aClass = student.getClass(); Method getName = aClass.getDeclaredMethod("getName"); long l = System.currentTimeMillis(); for (int i = 0; i < 1000000000; i++) { getName.invoke(student,null); } long l1 = System.currentTimeMillis(); System.out.println(l1-l); } //反射方式 关闭权限检测 较慢 public void t3() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Student student = new Student(); Class aClass = student.getClass(); Method getName = aClass.getDeclaredMethod("getName"); //关闭权限检测 getName.setAccessible(true); long l = System.currentTimeMillis(); for (int i = 0; i < 1000000000; i++) { getName.invoke(student,null); } long l1 = System.currentTimeMillis(); System.out.println(l1-l); }}
反射操作泛型
- java采用泛型擦除的机制来引入泛型,java中的泛型仅仅是给编译器javac使用的,确保数据的安全性和免去强制类型转换问题,但是,一旦编译完成,所有和泛型有关的类型全部擦除,为了通过反射操作这些类型,java新增了ParameterizedType、GenericArrayType、TypeVariable和WildcardType几种类型来代表不能被归一到Class类中的类型但是又和原始类型齐名的类型
- ParameterizedType:表示一种参数化类型,比如Collection
- GenericArrayType:表示一种元素类型是参数化类型或者类型变量的数组类型
- TypeVariable:是各种类型变量的公共父接口
- WildcardType:代表一种通配符类型表达式
package com.utils;import java.lang.reflect.Method;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;import java.util.List;import java.util.Map;public class Test32 { public void t1(Map<String,Student> map, List<Student> list){ System.out.println("t1"); } public Map<String,Student> t2(){ System.out.println("t2"); return null; } public static void main(String[] args) throws NoSuchMethodException { Method t1 = Test32.class.getMethod("t1", Map.class, List.class); Type[] genericParameterTypes = t1.getGenericParameterTypes(); for (Type genericParameterType : genericParameterTypes) { System.out.println(genericParameterType); System.out.println("-------------"); if (genericParameterType instanceof ParameterizedType){ Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments(); for (Type actualTypeArgument : actualTypeArguments) { System.out.println(actualTypeArgument); } } } System.out.println("---------------"); Method t2 = Test32.class.getMethod("t2"); Type genericReturnType = t2.getGenericReturnType(); if (genericReturnType instanceof ParameterizedType){ Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments(); for (Type actualTypeArgument : actualTypeArguments) { System.out.println(actualTypeArgument); } } }}
反射操作注解
ORM
Object relationship Mapping :对象关系映射
- 类和表结构对应
- 属性和字段对应
- 对象和记录对应
package com.utils;import java.lang.annotation.*;import java.lang.reflect.Field;@tableclass("cx_table")public class Test33 { @columnfield(columnName="tb_id",type="int",length=12) private int id; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { Class aClass = Class.forName("com.utils.Test33"); //通过反射获得注解 Annotation[] annotations = aClass.getAnnotations(); for (Annotation annotation : annotations) { System.out.println(annotation); } //获得注解的value的值 tableclass annotation = (tableclass)aClass.getAnnotation(tableclass.class); System.out.println(annotation.value()); //获得类指定的注解 Field ids = aClass.getDeclaredField("id"); columnfield annotation1 = ids.getAnnotation(columnfield.class); System.out.println(annotation1.columnName()); System.out.println(annotation1.type()); System.out.println(annotation1.length()); }}//类名的注解@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@interface tableclass{ String value();}//属性的注解@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)@interface columnfield{ String columnName(); String type(); int length();}
=========================================================
注解与反射 推荐狂神说
开发者涨薪指南 48位大咖的思考法则、工作方式、逻辑体系简谱吧