反射
概述
Reflection被视为动态语言的关键,反射机制允许程序在执行期借助于Reflection API取得任何类的内部信息,并能直接操作任意对象的内部属性及方法。
优点:可以实现动态创建对象和编译,体现出很大的灵活性
缺点:对性能有影响。使用反射基本上是一种解释操作,我们可以告诉JVM,我们希望做什么并且它满足我们的要求。这类操作总是慢于直接执行相同的操作
主要API:
- java.lang.Class:代表一个类
- java.lang.reflect.Method:代表一个类的方法
- java.lang.reflect.Field:代表一个类的成员变量
- java.lang.reflect.Constructor:代表一个类的构造器
- …
得到Class的几种方法
package com.nocilantro.Reflection;
public class Demo02 {
public static void main(String[] args) throws ClassNotFoundException {
Person person = new Student();
System.out.println(person.name);
// 方式一:通过对象获得
Class c1 = person.getClass();
System.out.println(c1.hashCode());
// 方式二:通过forName获得
Class c2 = Class.forName("com.nocilantro.Reflection.Student");
System.out.println(c2.hashCode());
// 方式三:通过类名.class获得
Class c3 = Student.class;
System.out.println(c3);
// 方式四:基本内置类型的包装类都有一个Type属性
Class<Integer> c4 = Integer.TYPE;
System.out.println(c4);
// 获得父类类型
Class c5 = c1.getSuperclass();
System.out.println(c5); // class com.nocilantro.Reflection.Person
}
}
class Person {
String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
class Student extends Person {
public Student() {
this.name = "学生";
}
}
class Teacher extends Person {
public Teacher() {
this.name = "老师";
}
}
所有类型的Class
package com.nocilantro.Reflection;
/**
* 所有类型的Class
*/
public class Demo03 {
public static void main(String[] args) {
Class c1 = Object.class; // 类
Class c2 = Comparable.class; // 接口
Class c3 = String[].class; // 一维数组
Class c4 = int[][].class; // 二维数组
Class c5 = Override.class; // 注解
Class c6 = Enum.class; // 枚举
Class c7 = Integer.class; // 基本数据类型
Class c8 = void.class; // void
Class c9 = Class.class; // Class
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
System.out.println(c4);
System.out.println(c5);
System.out.println(c6);
System.out.println(c7);
System.out.println(c8);
System.out.println(c9);
// 只要元素类型与维度一样,就是同一个Class
int[] a = new int[10];
int[] b = new int[100];
System.out.println(a.getClass().hashCode());
System.out.println(b.getClass().hashCode());
}
}
内存分析
加载 -> 链接 -> 初始化
什么时候会发生类初始化
- 类的主动引用(一定会发生类的初始化)
- 当虚拟机启动,先初始化main方法所在的类
- new一个类的对象
- 调用类的静态成员(除了final常量)和静态方法
- 使用java.lang.reflect包的方法对类进行反射调用
- 当初始化一个类,如果其父类没有被初始化,则先初始化它的父类
- 类的被动引用(不会发生类的初始化)
- 当访问一个静态域时,只有真正声明这个域的类才会被初始化。如:当通过子类引用父类的静态变量,不会导致子类的初始化
- 通过数组定义类引用,不会触发此类的初始化
- 引用常量不会触发此类的初始化(常量在链接阶段就存入调用类的常量池中了)
package com.nocilantro.Reflection;
/**
* 测试类什么时候会初始化
*/
public class Demo05 {
static {
System.out.println("main所在类被加载");
}
public static void main(String[] args) throws ClassNotFoundException {
// 主动引用
// Son son = new Son();
// 反射也会产生主动引用
// Class.forName("com.nocilantro.Reflection.Son");
// 不会产生类的引用的方法
// System.out.println(Son.b); // main类和父类被加载
// Son[] sons = new Son[5]; // 只有main类被加载
// System.out.println(Son.n); // 只有main类被加载
}
}
class Father {
static int b = 2;
static {
System.out.println("父类被加载");
}
}
class Son extends Father {
static {
System.out.println("子类被加载");
m = 300;
}
static int m = 100;
static final int n = 1;
}
获取运行时类的完整结构
package com.nocilantro.Reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 获得类的信息
*/
public class Demo06 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class c1 = Class.forName("com.nocilantro.Reflection.User");
// 获得类的名字
System.out.println(c1.getName()); // 包名+类名
System.out.println(c1.getSimpleName()); // 类名
// 获得类的属性
// Field[] fields = c1.getFields(); // 只能找到public属性
Field[] declaredFields = c1.getDeclaredFields(); // 找到全部属性
for (Field field : declaredFields) {
System.out.println(field);
}
System.out.println(c1.getDeclaredField("name"));
// 获得类的方法
System.out.println("---------------------getMethods()-------------------------------");
Method[] methods = c1.getMethods(); // 获得本类及父类的全部public方法
for (Method method : methods) {
System.out.println(method);
}
System.out.println("------------------------getDeclaredMethods()----------------------------");
Method[] declaredMethods = c1.getDeclaredMethods(); // 获得本类的全部方法
for (Method method : declaredMethods) {
System.out.println(method);
}
System.out.println("------------------------获得指定方法----------------------------");
Method getName = c1.getMethod("getName", null);
Method setName = c1.getMethod("setName", String.class);
System.out.println(getName);
System.out.println(setName);
System.out.println("------------------------获得构造器----------------------------");
Constructor[] declaredConstructors = c1.getDeclaredConstructors();
for (Constructor constructor : declaredConstructors) {
System.out.println(constructor);
}
System.out.println("------------------------获得指定构造器----------------------------");
Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
System.out.println(declaredConstructor);
}
}
有了Class对象,能做什么
- 创建类的对象:调用Class对象的newInstance()方法
- 类必须有一个无参构造器
- 类的构造器的访问权限需要足够
- 调用Constructor构造对象
package com.nocilantro.Reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Demo07 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
Class<?> c1 = Class.forName("com.nocilantro.Reflection.User");
// 构造对象
User user = (User) c1.newInstance(); // 本质上是调用了User的无参构造器
System.out.println(user);
// 通过构造器创建对象
Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
User user2 = (User) constructor.newInstance("Leo", 18, 001);
System.out.println(user2);
// 通过反射调用普通方法
// invoke(对象,方法值)
User user3 = (User) c1.newInstance();
Method setName = c1.getDeclaredMethod("setName", String.class);
setName.invoke(user3, "Qiuqiu");
System.out.println(user3);
// 通过反射操作属性
User user4 = (User) c1.newInstance();
Field name = c1.getDeclaredField("name");
// 不能直接操作私有属性,需要关闭程序的安全检测,属性或方法的setAccessible(true)
/**
* A value of {@code true} indicates that
* * the reflected object should suppress Java language access
* * checking when it is used.
*/
name.setAccessible(true); // 关闭程序的安全检测
name.set(user4, "Huhu");
System.out.println(user4.getName());
}
}
性能对比分析
package com.nocilantro.Reflection;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 性能对比分析
*/
public class Demo08 {
public static void test01() {
User user = new User();
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
user.getName();
}
long end = System.currentTimeMillis();
System.out.println("普通方法:" + (end - start) + "ms");
}
public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName");
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user, null);
}
long end = System.currentTimeMillis();
System.out.println("反射方法:" + (end - start) + "ms");
}
public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName");
getName.setAccessible(true);
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user, null);
}
long end = System.currentTimeMillis();
System.out.println("反射关闭检测方法:" + (end - start) + "ms");
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
test01();
test02();
test03();
}
}
反射操作泛型
package com.nocilantro.Reflection;
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 Demo09 {
public void test01(Map<User, String> map, List<User> users) {
System.out.println("test01");
}
public Map<User, String> test02() {
System.out.println("test02");
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
// 得到方法
Method test01 = Demo09.class.getDeclaredMethod("test01", Map.class, List.class);
//得到方法的泛型参数类型
Type[] types = test01.getGenericParameterTypes();
for (Type type : types) {
System.out.println("#:" + type); // 打印方法的泛型参数类型(Map<User, String>)
if (type instanceof ParameterizedType) {
// 将泛型参数类型强转为参数化类型,并得到实际的类型参数
Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
System.out.println("---------------------------------------------");
Method test02 = Demo09.class.getDeclaredMethod("test02", null);
Type type = test02.getGenericReturnType();
if (type instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
}
反射操作注解
package com.nocilantro.Reflection;
import java.lang.annotation.*;
import java.lang.reflect.Field;
/**
* 练习反射操作注解
*/
public class Demo10 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("com.nocilantro.Reflection.Student2");
// 通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
// 获得注解value的值
TableLeo annotation = (TableLeo) c1.getAnnotation(TableLeo.class);
String value = annotation.value();
System.out.println(value);
// 获得类指定的注解
Field name = c1.getDeclaredField("name");
FieldAnnotation annotation1 = name.getAnnotation(FieldAnnotation.class);
System.out.println(annotation1.columnName());
System.out.println(annotation1.type());
System.out.println(annotation1.length());
}
}
@TableLeo("db_student")
class Student2 {
@FieldAnnotation(columnName = "db_id", type = "int", length = 10)
private int id;
@FieldAnnotation(columnName = "db_name", type = "String", length = 10)
private String name;
@FieldAnnotation(columnName = "db_age", type = "int", length = 3)
private int age;
public Student2() {
}
public Student2(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student2{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
// 类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableLeo{
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldAnnotation {
String columnName();
String type();
int length();
}