1. 类加载器
1.1 类加载
当程序要使用某个类时,如果该类还未被加载到内存中,则系统会通过类的加载、类的连接、类的初始化三个步骤来对类进行初始化。这三个步骤成为类加载或类初始化。
类的加载
- 就是指将class文件读入内存,并为之创建java.lang.Class对象
- 任何类被使用时,系统都会为之建立一个java.lang.Class对象
类的连接
- 验证阶段:用于检验被加载的类是否有正确的内部结构,并和其他类协调一致
- 准备阶段:负责为类的类变量分配内存,并设置默认初始化值
- 解析阶段:将类的二进制数据中的符号引用替换为直接引用
类的初始化
- 在该阶段主要是对类变量进行初始化
当系统使用一个类时,该类以及其所有父类都会被进行初始化
1.2 类加载器
作用:
负责将.class文件加载到内存中,并为之生成对应的java.lang.Class对象
JVM的类加载机制:
- 全盘负责:当一个类加载器负责加载某个Class时,该Class所依赖的和引用的其他Class也将由该类加载器负责载入,除非显示使用另外一个类加载器来载入
- 父类委托:当类加载器负责加载某个Class时,先让父类加载器试图加载该类Class,只有在父类加载器无法加载该类时才尝试从自己的类路径中加载该类。
- 缓存机制:保证所有加载过的Class都会被缓存,当程序需要使用某个Class对象时,类加载器先从缓存区中搜索该Class,只有当缓存区中不存在该Class对象时,系统才会读取该类的二进制数据,并将其转换成Class对象,存储到缓存区
ClassLoader:是负责加载类的对象
ClassLoader的两个方法:
static ClassLoader getSystemClassLoader() :返回用于委派的系统类加载器。
ClassLoader getParent() :返回父类加载器进行委派。
类加载器的继承关系:System的父类加载器为Platform,而Platform的父类加载器为Bootstrap
package Java37.Demo1;
public class demo1 {
public static void main(String[] args) {
//static ClassLoader getSystemClassLoader() :返回用于委派的系统类加载器。
ClassLoader c = ClassLoader.getSystemClassLoader();
System.out.println(c);//AppClassLoader
//ClassLoader getParent() :返回父类加载器进行委派。
ClassLoader c2 = c.getParent();
System.out.println(c2);//ExtClassLoader
ClassLoader c3 = c2.getParent();
System.out.println(c3);
}
}
2. 反射
java反射机制:是指在运行时获取一个类的变量和方法信息。然后通过获取到的信息来创建对象,调用方法的一种机制。由于这种动态性,可以极大增强程序灵活性,程序不用在编译期完成确定。
1.1 获取Class类的对象
要通过反射去使用一个类,需要先获取该类的字节码文件对象,也就是类型为Class类型的对象。
三种方式获取Class类型的对象:
- 使用类的Class属性获取该类对应的Class对象。如:Student.class
- 调用对象的getClass()方法,返回该对象所属类对应的Class对象
该方法是Object类中的方法,所有java对象都可以调用该方法 - 使用Class类中的静态方法forName(String className),该方法需要传入字符串参数,该字符串参数的值是某个类的全路径,也就是完整报名的路径
package Java37.Demo1;
/*
- 使用类的Class属性获取该类对应的Class对象。如:Student.class
- 调用对象的getClass()方法,返回该对象所属类对应的Class对象
该方法是Object类中的方法,所有java对象都可以调用该方法
- 使用Class类中的静态方法forName(String className),该方法需要传入字符串参数,
该字符串参数的值是某个类的全路径,也就是完整报名的路径
* */
public class ReflectDemo {
public static void main(String[] args) throws ClassNotFoundException {
//方式1:使用类的Class属性获取该类对应的Class对象。
Class<Student> c1 = Student.class;
System.out.println(c1);
Class<Student> c2 = Student.class;
System.out.println(c1==c2);//true,一个类在内存中只有一个字节码文件对象
System.out.println("---------------");
//方式2:调用对象的getClass()方法,返回该对象所属类对应的Class对象
Student s = new Student();
Class<? extends Student> c3 = s.getClass();
System.out.println(c1==c3);//表示getClass也能调用字节码文件对象
//方法2:使用Class类中的静态方法forName(String className),该方法需要传入字符串参数
Class<?> c4 = Class.forName("Java37.Demo1.Student");
System.out.println(c1==c4);
}
}
1.2 反射获取构造方法并使用
package Java37.Demo2;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
//反射获取构造方法并使用
public class demo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//获取Class对象
Class<?> c = Class.forName("Java37.Demo1.Student");
//Constructor<?>[] getConstructors()
//返回包含一个Constructor对象的数组,Constructor对象反映了由该Class对象表示的类的所有公共构造函数。
Constructor<?>[] cons = c.getConstructors();
for (Constructor con:cons){
System.out.println(con);
//只看见两个构造方法,getConstructors()只能获取类中的公共(public)构造方法,无法获取默认和私有
}
//Constructor<?>[] getDeclaredConstructors()
//返回反映有该class对象表示的类声明的所有构造函数的Constructor对象的数组
Constructor<?>[] dcons = c.getDeclaredConstructors();
for (Constructor con:dcons){
System.out.println(con);
//可以获取所有的构造方法
}
System.out.println("----------");
//Constructor<T> getConstructor(Class<?>... parameterTypes)
//返回一个 Constructor对象,该对象反映由该Class对象表示的类的指定公共(public)构造函数。
//参数:要获取构造方法的参数的个数和数据类型对应的字节码文件对象
Constructor<?> con = c.getConstructor();
//Constructor提供了一个类的单个构造函数的信息和访问。
//T newInstance(Object... initargs)
//使用此 Constructor对象表示的构造函数,使用指定的初始化参数来创建和初始化构造函数的声明类的新实例。
Object obj = con.newInstance();//反射创建镀锡
System.out.println(obj);
//Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
//返回一个 Constructor对象,该对象反映由该Class对象表示的类的指定构造函数。
}
}
Class类中用于获取构造方法的方法:
- Constructor<?>[] getConstructors():返回所有公共构造方法对象的数组
- Constructor<?>[] getDeclaredConstructors():返回所有构造方法对象的数组
- Constructor getConstructor(Class<?>… parameterTypes):返回单个公共构造方法对象
- Constructor getDeclaredConstructor(Class<?>… parameterTypes):返回单个构造方法对象
Constructor类中用于创建对象的方法:
- T newInstance(Object… initargs):根据指定的构造方法创建对象
1.3 反射获取构造方法并使用练习
练习1:通过反射实现如下操作
- Student s = new Student(“林青霞”,30,“西安”);
- System.out.println(s);
- 基本数据类型也可以通过.class得到对应的Class类型
package Java37.Demo2;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class demo2 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//获取Class对象
Class<?> c = Class.forName("Java37.Demo1.Student");
//获取带三个参数的构造方法对象,Constructor<T> getConstructor(Class<?>... parameterTypes)
//public Student(String name, int age,String address)
Constructor<?> con = c.getConstructor(String.class, int.class, String.class);
//基本数据类型也可以通过.class得到对应的Class类型
//通过反射获取对应的构造方法创建对象
Object obj = con.newInstance("林青霞", 30, "西安");
System.out.println(obj);
}
}
练习2:通过反射实现如下操作
- Student s = new Student(“林青霞”);
- System.out.println(s);
- public void setAccessible(boolean flag):值为true,取消访问检查,从而实现对私有构造方法创建对象
package Java37.Demo2;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
// - Student s = new Student("林青霞");
// - System.out.println(s);
public class demo3 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//获取Class对象
Class<?> c = Class.forName("Java37.Demo1.Student");
//获取类中的构造方法对象, private Student(String name)
Constructor<?> dcon = c.getDeclaredConstructor(String.class);
//暴力反射,通过私有构造方法创建对象
//public void setAccessible(boolean flag):值为true,取消访问检查
dcon.setAccessible(true);
//创建对象并输出
Object obj = dcon.newInstance("林青霞");
System.out.println(obj);
}
}
1.4 反射获取成员变量并使用
Class类中用于获取成员变量的方法:
- Field[] getFields():返回所有公共成员变量对象的数组
- Field[] getDeclaredFields():返回所有成员变量对象的数组
- Field[] getField(String name):返回单个公共成员变量对象
- Field[] getDeclaredField(String name):返回单个成员变量对象
Field类中用于给成员变量赋值的方法
- void set(Object obj,Object value):给obj对象的成员变量赋值为value
package Java37.Demo3;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
//反射获取成员变量并使用
public class demo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//获取Class对象
Class<?> c = Class.forName("Java37.Demo1.Student");
//Field[] getFields() 返回一个包含Field对象的数组,Field对象反映由该Class对象表示的类或接口的所有可访问公共字段
//Field[] getDeclaredFields() 返回一个Field对象的数组,反映由该Class对象表示的类或接口声明的所有字段
// Field[] fields = c.getFields();//获取类中公共成员变量
Field[] fields = c.getDeclaredFields();//获取类中所有成员变量
for (Field field:fields){
System.out.println(field);
}
//Field[] getField(String name) 返回一个Field对象,Field对象反映由该Class对象表示的类或接口的指定公共成员字段
//Field[] getDeclaredField(String name) 返回一个Field对象,反映由该Class对象表示的类或接口的指定声明字段
Field addressField = c.getField("address");
//Field提供有关类或接口的单个字段的信息和动态访问。
//获取无参构造方法创建对象
Constructor<?> con = c.getConstructor();
Object obj = con.newInstance();
//void set(Object obj, Object value)
//将指定对象参数上的此 Field对象表示的字段设置为指定的新值。
addressField.set(obj,"西安");//给obj的成员变量addressField赋值为西安
System.out.println(obj);
// //成员变量使用
// Student s = new Student();
// s.address = "西安";
// System.out.println(s);
}
}
1.6 反射获取成员变量并使用练习
练习:通过反射实现如下操作
- Student s = new Student();
- s.name = “林青霞”;
- s.age = 30;
- s.address = “西安”;
- System.out.println(s);
package Java37.Demo3;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
/*
练习:通过反射实现如下操作
- Student s = new Student();
- s.name = "林青霞";
- s.age = 30;
- s.address = "西安";
- System.out.println(s);
- */
public class demo1 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
//创建Class对象
Class<?> c = Class.forName("Java37.Demo1.Student");
//获取无参构造方法创建对象
Constructor<?> con = c.getConstructor();
Object obj = con.newInstance();
//获取成员变量,并赋值
Field nameField = c.getDeclaredField("name");
//name是私有变量不能使用getField,另外私有成员变量不能直接使用,需要暴力反射
nameField.setAccessible(true);
nameField.set(obj,"林青霞");
Field ageField = c.getDeclaredField("age");
ageField.setAccessible(true);
ageField.set(obj,30);
Field addressField = c.getDeclaredField("address");
addressField.setAccessible(true);
addressField.set(obj,"西安");
System.out.println(obj);
}
}
1.7 反射获取成员方法并使用
Class中用于获取成员方法的方法
- Method[] getMethods():返回所有公共成员方法对象的数组,包括继承的
- Method[] getDeclaredMethods():返回所有成员方法对象数组,不包括继承的
- Method getMethod(String name, Class<?>… parameterTypes):返回单个公共成员方法对象
- Method getDeclaredMethod(String name, Class<?>… parameterTypes)返回单个成员方法对象
Method中用于调用成员方法的方法:
- Object invoke(Object obj, Object… args):调用Object对象的成员方法,参数时args,返回值是Object类型
package Java37.Demo4;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//反射获取成员方法并使用
public class demo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//获取class对象
Class<?> c = Class.forName("Java37.Demo1.Student");
//Method[] getMethods()
//返回包含一个数组 Method对象反射由此表示的类或接口的所有公共方法,包括那些由类或接口和那些从超类和超接口继承的声明。
//Method[] getDeclaredMethods()
//返回包含一个数组 方法对象反射的类或接口的所有声明的方法,通过此表示 类对象,包括公共,保护,默认(包)访问和私有方法,但不包括继承的方法。
// Method[] methods = c.getMethods();
Method[] methods = c.getDeclaredMethods();
for (Method method:methods){
System.out.println(method);
}
System.out.println("------------");
//Method getMethod(String name, Class<?>... parameterTypes)
//返回一个方法对象,它反映此表示的类或接口的指定公共成员方法 类对象。
//Method getDeclaredMethod(String name, Class<?>... parameterTypes)
//返回一个 方法对象,它反映此表示的类或接口的指定声明的方法 类对象
//获取method1,public void method1()
Method m = c.getMethod("method1");
// Method提供有关类和接口上单一方法的信息和访问权限
//获取无参构造方法创建对象
Constructor<?> dcon = c.getConstructor();
Object obj = dcon.newInstance();
//Object invoke(Object obj, Object... args)
//在具有指定参数的指定对象上调用此方法对象表示的底层方法。
//Object:返回值类型
//obj:调用方法的对象
//args:方法需要的参数
m.invoke(obj);
/*
* Student s = new Student();
* s.method1;
* */
}
}
1.8 反射获取成员方法并使用练习
练习:通过反射实现如下操作
- Student s = new Student();
- s.method1
- s.method2(“林青霞”);
- String ss = s.method3(“林青霞”,30);
- System.out.println(ss);
- s.function();
package Java37.Demo4;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/*
练习:通过反射实现如下操作
- Student s = new Student();
- s.method1
- s.method2("林青霞");
- String ss = s.method3("林青霞",30);
- System.out.println(ss);
- s.function();
* */
public class demo1 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//获取Class对象
Class<?> c = Class.forName("Java37.Demo1.Student");
//获取无参构造方法创建对象 Student s = new Student();
Constructor<?> con = c.getConstructor();
Object obj = con.newInstance();
//获取成员方法
Method method1Method = c.getDeclaredMethod("method1");
method1Method.invoke(obj);
Method method2Method = c.getDeclaredMethod("method2", String.class);
method2Method.invoke(obj,"林青霞");
//String ss = s.method3("林青霞",30);
Method method3Method = c.getDeclaredMethod("method3", String.class, int.class);
Object ss = method3Method.invoke(obj, "林青霞", 30);
System.out.println((String) ss);
Method function = c.getDeclaredMethod("function");
//私有方法,暴力反射
function.setAccessible(true);
function.invoke(obj);
}
}
1.9 反射练习
练习1:有一个ArrayList< Integer >集合,在这个集合中添加字符串数据,如何实现?
package Java37.Demo4;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
public class demo2 {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//创建集合
ArrayList<Integer> array = new ArrayList<Integer>();
array.add(10);
array.add(20);
array.add(30);
// array/array("hello");
//通过反射拿到add方法添加字符串数据
Class<? extends ArrayList> c = array.getClass();
Method m = c.getMethod("add", Object.class);
m.invoke(array,"hello");
m.invoke(array,"world");
System.out.println(array);
}
}
练习2:通过配置文件运行类中的方法
package Java37.Demo4;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
public class demo3 {
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
// Student s = new Student();
// s.study();
// Teacher t = new Teacher();
// t.teach();
/*
* class.txt
* className = xxx
* methodName = xxx
* */
//加载数据
Properties pro = new Properties();
FileReader fr = new FileReader("D:\\lyy\\class.txt");
pro.load(fr);
fr.close();
// className = Java37.Demo4.Student
// methodName = study
String className = pro.getProperty("className");
String methodName = pro.getProperty("methodName");
//通过反射来使用
Class<?> c = Class.forName("Java37.Demo4.Student");
Constructor<?> con = c.getConstructor();
Object obj = con.newInstance();
Method m = c.getMethod("study");
m.invoke(obj);
}
}