文章目录
一、反射机制概述
概述:反射机制是在运行状态中,对于任意一个类,都能知道这个类的所有属性和方法,对于任意一个对象,都能够调用它的方法和属性。这种动态获取信息以及动态调用对象方法的功能我们称为Java语音的反射机制
静态编译:在编译时确定类型,绑定对象
动态编译:在运行时确定类型,绑定对象
优缺点
优点:运行期类型的判断,动态加载类,代码灵活度高
缺点:性能的瓶颈,反射相当于一系列的解释操作,通知jvm要做的事情,性能直接比Java代码要慢的多
Java反射机制提供的功能:
运行时判断任意一个对象所属的类
运行时构造任意一个类的对象
运行时判断任意一个类所具有的成员变量和方法
运行时判断调用任意一个对象的成员变量和方法
运行时获取泛型信息和注解信息
生成动态代理
框架=反射+注解+设计模式
二、理解Class类并获取Class实例
1.反射之前类的实例化操作
package com.ming.reflection;
import org.junit.Test;
/**
* 反射
*/
public class ReflectionTest {
//反射之前,类的实例化操作
@Test
public void test1() {
//1.创建对象
Person p1 = new Person("Tom", 12);
//2.通过对象调用内部的属性和方法
p1.setAge(10);
System.out.println(p1.toString());
p1.show();
//在Person类的外部,不可以通过Person类的对象调用Person类的私有结构
//比如私有的属性name和showNation()方法以及私有的构造器,封装性的限制
}
}
2.使用反射获取实例
//使用反射对Person类操作
@Test
public void test2() throws Exception {
Class clazz = Person.class;
//1.通过反射创建Person类的对象
Constructor cons = clazz.getConstructor(String.class, int.class);
Object obj = cons.newInstance("Tom", 12);
Person p = (Person) obj;
System.out.println(p.toString());
//2.通过反射调用对象指定的属性和方法
//调用属性
Field age = clazz.getDeclaredField("age");
age.set(p, 10);
System.out.println(age.get(p));
System.out.println(p.toString());
//调用方法
Method show = clazz.getDeclaredMethod("show");
show.invoke(p);
}
1.通过直接new对象或反射的方式都可以调用公共的结构,开发中依然用new关键字创建对象?
什么时候用反射?反射的特征:动态性
2.反射的机制与面向对象的封装性矛盾(封装后私有的结构外部是不可以调用的,而反射是可以调用的)?
反射是能调用私有的,而封装是建议你去调用公有的
3.Class类的理解
java.lang.class类的理解
1.类的加载过程
程序经过java.exe命令后生成一个或多个字节码文件以.class结尾。
接着使用java.exe命令对某个字节码文件进行解释运行。相当于将某个字节码文件加载到内存中,此过程就叫做类的加载。加载到内存中的类就叫做运行时类,此运行时的类,就作为Class的一个实例。
2.Class的实例就对应着一个运行时类
3.加载到内存中的运行时类,会缓存一定的时间,在此时间类,我们可以通过不同的方式来获取次运行时类
4.class实例的获取
/**
* class类的实例获取
*/
@Test
public void test3() throws ClassNotFoundException {
//方式一:调用运行时类的属性.class
Class<Person> clazz1 = Person.class;
System.out.println(clazz1);
//方式二:通过运行时类的对象,调用getClass()
Person p = new Person();
Class clazz2 = p.getClass();
System.out.println(clazz2);
//方式三:调用class类的静态方法forName(String classpath)
Class clazz3 = Class.forName("com.ming.reflection.Person");
//clazz3 = Class.forName("java.lang.String");
System.out.println(clazz3);
//以下返回true
System.out.println(clazz1 == clazz2);
System.out.println(clazz1 == clazz3);
//方式四:使用类的加载器
ClassLoader classLoader = ReflectionTest.class.getClassLoader();
Class clazz4 = classLoader.loadClass("com.ming.reflection.Person");
System.out.println(clazz4);
//返回true
System.out.println(clazz1 == clazz4);
}
三、类的加载与ClassLoader的理解
1.类的加载过程
当程序使用某个类的时候,如果该类还未被加载到内存中,则系统会通过以下三个步骤进行初始化
类的加载Load:将类的class文件读入到内存中,并为之创建一个java.lang.Class对象。此过程由类的加载完成
类的链接Link:将类的二进制数据合并到JRE中
类的初始化Initialize:JVM负责对类初始化
2.ClassLoader
类加载器的作用:将class文件字节码内容加载到内存中,并将这些静态数据转换成方法区的运行时数据结构,然后再堆内存中生成一个代表这个类的java.lang.class对象,作为方法区中类数据的访问入口
四、创建运行时类的对象
1.newInstance()创建运行时类的对象
要求:
1.运行时类必须提供无参构造器
2.空参的构造器的访问权限得够,通常是public
@Test
public void test1() throws IllegalAccessException, InstantiationException {
Class<Person> clazz = Person.class;
Person person = clazz.newInstance();
System.out.println(person);
}
在javabean中要求提供一个空参的构造器,原因是便于通过反射创建运行时类的对象,便于子类继承父类时,默认调用super()时,保证父类有次构造器
2.反射的动态性
@Test
public void test2() throws Exception {
int random = new Random().nextInt(3);
String classPath = "";
switch (random) {
case 0:
classPath = "java.util.Date";
break;
case 1:
classPath = "java.lang.Object";
break;
case 2:
classPath = "com.ming.reflection.Person";
break;
}
Object instance = getInstance(classPath);
System.out.println(instance);
}
/**
* 体现反射的多态性
*
* @param classPath 指定的全限定类名
* @return 返回一个指定类的对象
* @throws Exception
*/
public static Object getInstance(String classPath) throws Exception {
Class clazz = Class.forName(classPath);
Object instance = clazz.newInstance();
return instance;
}
五、获取运行时类的完整结构
1.获取属性结构
getFields()获取当前运行时类及其父类中public访问权限中的属性
getDeclaredFields()获取当前运行时类中声明的所有属性(不包含父类中声明的属性)
@Test
public void test3(){
Class clazz = Person.class;
//获取属性结构
//getFields获取当前运行时类及其父类中public访问权限中的属性
Field[] fields = clazz.getFields();
for (Field field : fields) {
System.out.println(field);
}
//getDeclaredFields获取当前运行时类中声明的所有属性(不包含父类中声明的属性)
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
System.out.println(field);
}
}
2.获取属性的完整结构
//属性有:权限修饰符、数据类型,变量名
@Test
public void test4() {
Class clazz = Person.class;
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
//1.权限修饰符
int modifier = field.getModifiers();
System.out.print(Modifier.toString(modifier) + "\t");
//2.数据类型
Class type = field.getType();
System.out.print(type.getName() + "\t");
//3.变量名
String name = field.getName();
System.out.print(name);
System.out.println();
}
}
3.获取所有的方法
获取所有的方法:getMethods()获取当前运行时类及其父类中声明为public的方法
getDeclaredMethods():获取当前运行时类中声明的所有方法(不包含父类中声明的方法)
/**
* 获取运行时类的方法结构
*/
@Test
public void test5(){
Class clazz = Person.class;
//获取所有的方法:getMethods()获取当前运行时类及其父类中声明为public的方法
Method[] methods = clazz.getMethods();
for (Method method : methods) {
System.out.println(method);
}
System.out.println();
//getDeclaredMethods():获取当前运行时类中声明的所有方法(不包含父类中声明的方法)
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
System.out.println(declaredMethod);
}
}
4.获取方法的内部结构
@ 注解
方法:权限修饰符、返回值类型、方法名(形参1、形参2) throws XXException { }
/**
* @ 注解
* 方法:权限修饰符、返回值类型、方法名(形参1、形参2) throws XXException { }
*/
@Test
public void test6() {
Class clazz = Person.class;
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method method : declaredMethods) {
//1.获取方法声明的注解
Annotation[] annotations = method.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
//2.权限修饰符
int modifiers = method.getModifiers();
System.out.print(Modifier.toString(modifiers) + "\t");
//3.返回值类型
Class returnType = method.getReturnType();
System.out.print(returnType.getName() + "\t");
//4.方法名
System.out.print(method.getName());
System.out.print("(");
//5.形参列表
Class[] parameterTypes = method.getParameterTypes();
//有参数类型
if (!(parameterTypes == null && parameterTypes.length == 0)) {
for (int i = 0; i < parameterTypes.length; i++) {
if (i == parameterTypes.length - 1) {
System.out.print(parameterTypes[i].getName() + " args_" + i);
break;
}
System.out.print(parameterTypes[i].getName() + " args_" + i + ",");
}
}
System.out.print(")");
//6.抛出的异常
Class[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length > 0) {
System.out.print(" throws ");
for (int i = 0; i < exceptionTypes.length; i++) {
if (i == exceptionTypes.length - 1) {
System.out.print(exceptionTypes[i].getName());
break;
}
System.out.print(exceptionTypes[i].getName() + ",");
}
}
System.out.println();
}
}
5.获取运行时类的构造器
@Test
public void test7(){
Class clazz = Person.class;
//getConstructors:获取当前运行时类中public的构造器
Constructor[] constructors = clazz.getConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
System.out.println();
//getDeclaredConstructors:获取当前运行时类中所有的构造器
Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
for (Constructor declaredConstructor : declaredConstructors) {
System.out.println(declaredConstructor);
}
}
6.获取运行时类的父类及父类的泛型
/**
* 获取运行时的父类
*/
@Test
public void test8(){
Class clazz = Person.class;
Class superclass = clazz.getSuperclass();
System.out.println(superclass);
}
/**
* 获取运行时的带泛型的父类
*/
@Test
public void test9(){
Class clazz = Person.class;
Type genericSuperclass = clazz.getGenericSuperclass();
System.out.println(genericSuperclass);
}
/**
* 获取运行时的带泛型的父类的泛型
*/
@Test
public void test10(){
Class clazz = Person.class;
Type genericSuperclass = clazz.getGenericSuperclass();
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
//获取泛型类型
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
// System.out.println(actualTypeArgument.getTypeName());
System.out.println(((Class)actualTypeArgument).getName());
}
}
7.获取运行时类的接口、所在的包和注解
/**
* 获取运行时类实现的接口和父类的接口
*/
@Test
public void test11(){
Class clazz = Person.class;
Class[] interfaces = clazz.getInterfaces();
for (Class anInterface : interfaces) {
System.out.println(anInterface);
}
System.out.println();
Class superclass = clazz.getSuperclass();
Class[] interfaces1 = superclass.getInterfaces();
for (Class aClass : interfaces1) {
System.out.println(aClass);
}
}
/**
* 获取运行时类所在的包
*/
@Test
public void test12(){
Class clazz = Person.class;
Package aPackage = clazz.getPackage();
System.out.println(aPackage);
}
/**
* 获取运行时类声明的注解
*/
@Test
public void test13(){
Class clazz = Person.class;
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
}
六、调用运行时类的指定结构
调用运行时类中指定的结构:属性、方法、构造器
/**
* 调用运行时类中指定的结构:属性、方法、构造器
*/
@Test
public void testFiled() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
Class clazz = Person.class;
//创建运行时类的对象
Person p = (Person) clazz.newInstance();
//获取指定的属性:要求运行类中的属性为public,通常不用getField()
Field age = clazz.getField("age");
//设置当前属性的值
age.set(p, 12);
//获取当前属性的值
int ages = (int) age.get(p);
System.out.println(ages);
}
@Test
public void testFiled1() throws Exception {
Class clazz = Person.class;
//创建运行时类的对象
Person p = (Person) clazz.newInstance();
//获取运行时类指定变量名的属性
Field name = clazz.getDeclaredField("name");
//保证当前属性是可以访问的
name.setAccessible(true);
//设置指定对象的此属性值
name.set(p, "王五");
String s = (String) name.get(p);
System.out.println(s);
}
方法
@Test
public void testMethod() throws Exception {
Class clazz = Person.class;
//创建运行时类的对象
Person p = (Person) clazz.newInstance();
//获取指定的某个方法:参数1获取方法的名称、参数2指明获取方法的形参列表
Method method = clazz.getDeclaredMethod("showNation",String.class);
method.setAccessible(true);
//invoke():参数1方法的调用者,参数2方法的实参,invoke返回值对应类中方法的返回值String
String s = (String) method.invoke(p, "中国");
System.out.println(s);
System.out.println("***********如何调用静态方法**************");
Method info = clazz.getDeclaredMethod("info");
info.setAccessible(true);
//如果调用运行时类中的方法没有返回值就是类
Object invoke = info.invoke(Person.class);
System.out.println(invoke);//null
}
构造器
@Test
public void constructorTest() throws Exception {
Class clazz = Person.class;
//创建运行时类的对象,newInstance调用的是空参的构造器
//Person p = (Person) clazz.newInstance();
//获取指定的构造器,指明构造器的参数列表String.class
Constructor declaredConstructor = clazz.getDeclaredConstructor(String.class);
//保证此构造器是可以访问的
declaredConstructor.setAccessible(true);
//调用此构造器,构造器的作用就是创建对象
Person person = (Person) declaredConstructor.newInstance("tom");
System.out.println(person);
}