文章目录
-
- 1. Java 反射机制原理示意图
-
- 1.1 反射相关的主要类
- 1.2 反射的优点和缺点
- 1.3 反射调用优化-关闭访问检查
- 2. Class 类
-
- 2.1 基本介绍
- 2.2 Class类的常用方法
- 2.3 获取 Class 类对象
- 3. 哪些类型有 Class 对象
- 4. 类加载
-
- 4.1 基本说明
- 4.2 类加载时机
- 4.3 类加载过程图
- 4.4 类加载各阶段完成任务
- 4.5 加载阶段
- 4.6 连接阶段-验证
- 4.7 连接阶段-准备
- 5. 连接阶段-解析
- 6. Initialization(初始化)
- 5. 通过反射获取类的结构信息
-
- 5.1 第一组:java.lang.Class 类
- 5.2 第二组:java.lang.reflect.Field 类
- 5.3 第三组: java.lang.reflect.Method 类
- 5.4 第四组:java.lang.reflect.Constructor 类
- 6. 通过反射创建对象
- 7. 通过反射访问类中的成员
-
- 7.1 访问属性 ReflecAccessProperty.java
- 7.2 访问方法 ReflecAccessMethod.java
- 8. 本章作业
1. Java 反射机制原理示意图
1.1 反射相关的主要类
package com.xjz.reflection;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Properties;
public class Reflection01 {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\re.properties"));
String classfullpath = properties.get("classfullpath").toString();
String methodName = properties.get("method").toString();
Class cls = Class.forName(classfullpath);
Object o = cls.newInstance();
System.out.println("o 的运行类型=" + o.getClass());
Method method = cls.getMethod(methodName);
System.out.println("=======================");
method.invoke(o);
Field ageField = cls.getField("age");
System.out.println(ageField.get(o));
Constructor constructor = cls.getConstructor();
System.out.println(constructor);
Constructor constructor2 = cls.getConstructor(String.class);
System.out.println(constructor2);
}
}
1.2 反射的优点和缺点
1.3 反射调用优化-关闭访问检查
package com.xjz.reflection;
import com.xjz.Cat;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Reflection02 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
m1();
m2();
m3();
}
public static void m1() {
Cat cat = new Cat();
long start = System.currentTimeMillis();
for (int i = 0; i < 900000000; i++) {
cat.hi();
}
long end = System.currentTimeMillis();
System.out.println("m1() 耗时=" + (end - start));
}
public static void m2() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class cls = Class.forName("com.xjz.Cat");
Object o = cls.newInstance();
Method hi = cls.getMethod("hi");
long start = System.currentTimeMillis();
for (int i = 0; i < 900000000; i++) {
hi.invoke(o);
}
long end = System.currentTimeMillis();
System.out.println("m2() 耗时=" + (end - start));
}
public static void m3() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class cls = Class.forName("com.xjz.Cat");
Object o = cls.newInstance();
Method hi = cls.getMethod("hi");
hi.setAccessible(true);
long start = System.currentTimeMillis();
for (int i = 0; i < 900000000; i++) {
hi.invoke(o);
}
long end = System.currentTimeMillis();
System.out.println("m3() 耗时=" + (end - start));
}
}
2. Class 类
2.1 基本介绍
package com.xjz.reflection.class_;
import com.xjz.Cat;
public class Class01 {
public static void main(String[] args) throws ClassNotFoundException {
Class<?> cls1 = Class.forName("com.xjz.Cat");
Class<?> cls2 = Class.forName("com.xjz.Cat");
System.out.println(cls1.hashCode());
System.out.println(cls2.hashCode());
Class<?> cls3 = Class.forName("com.xjz.Dog");
System.out.println(cls3.hashCode());
}
}
2.2 Class类的常用方法
package com.xjz.reflection.class_;
import com.xjz.Car;
import java.lang.reflect.Field;
public class Class02 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
String classAllPath = "com.xjz.Car";
Class cls = Class.forName(classAllPath);
System.out.println(cls);
System.out.println(cls.getPackage().getName());
System.out.println(cls.getName());
Car car = (Car) cls.newInstance();
System.out.println(car);
Field brand = cls.getField("brand");
System.out.println(brand.get(car));
brand.set(car,"奔驰");
System.out.println(brand.get(car));
System.out.println("======所有的属性字段======");
Field[] fields = cls.getFields();
for (Field f : fields) {
System.out.println(f.getName());
}
}
}
2.3 获取 Class 类对象
package com.xjz.reflection.class_;
import com.xjz.Car;
public class GetClass_ {
public static void main(String[] args) throws ClassNotFoundException {
String classAllPath = "com.xjz.Car";
Class<?> cls1 = Class.forName(classAllPath);
System.out.println(cls1);
Class cls2 = Car.class;
System.out.println(cls2);
Car car = new Car();
Class cls3 = car.getClass();
System.out.println(cls3);
ClassLoader classLoader = car.getClass().getClassLoader();
Class cls4 = classLoader.loadClass(classAllPath);
System.out.println(cls4);
System.out.println(cls1.hashCode());
System.out.println(cls2.hashCode());
System.out.println(cls3.hashCode());
System.out.println(cls4.hashCode());
Class<Integer> integerClass = int.class;
Class<Character> characterClass = char.class;
Class<Boolean> booleanClass = boolean.class;
System.out.println(integerClass);
Class<Integer> type1 = Integer.TYPE;
Class<Character> type2 = Character.TYPE;
System.out.println(type1);
System.out.println(integerClass.hashCode());
System.out.println(type1.hashCode());
}
}
3. 哪些类型有 Class 对象
package com.xjz.reflection.class_;
import com.sun.org.apache.bcel.internal.classfile.Deprecated;
import java.io.Serializable;
public class AllTypeClass {
public static void main(String[] args) {
Class<String> cls1 = String.class;
Class<Serializable> cls2 = Serializable.class;
Class<Integer[]> cls3 = Integer[].class;
Class<float[][]> cls4 = float[][].class;
Class<Deprecated> cls5 = Deprecated.class;
Class<Thread.State> cls6 = Thread.State.class;
Class<Long> cls7 = long.class;
Class<Void> cls8 = void.class;
Class<Class> cls9 = Class.class;
System.out.println(cls1);
System.out.println(cls2);
System.out.println(cls3);
System.out.println(cls4);
System.out.println(cls5);
System.out.println(cls6);
System.out.println(cls7);
System.out.println(cls8);
System.out.println(cls9);
}
}
4. 类加载
4.1 基本说明
4.2 类加载时机
4.3 类加载过程图
4.4 类加载各阶段完成任务
4.5 加载阶段
4.6 连接阶段-验证
4.7 连接阶段-准备
package com.xjz.reflection.classLoad_;
public class ClassLoad02 {
public static void main(String[] args) {
}
}
class A {
public int n1 = 10;
public static int n2 = 20;
public static final int n3 = 30;
}
5. 连接阶段-解析
6. Initialization(初始化)
package com.xjz.reflection.classLoad_;
public class ClassLoad03 {
public static void main(String[] args) {
B b = new B();
}
}
class B {
static {
System.out.println("B 静态代码块执行");
num = 300;
}
static int num = 100;
public B() {
System.out.println("B() 构造器执行");
}
}
5. 通过反射获取类的结构信息
5.1 第一组:java.lang.Class 类
5.2 第二组:java.lang.reflect.Field 类
5.3 第三组: java.lang.reflect.Method 类
5.4 第四组:java.lang.reflect.Constructor 类
package com.xjz.reflection;
import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionUtils {
public static void main(String[] args) {
}
@Test
public void api_02() throws ClassNotFoundException {
Class<?> personCls = Class.forName("com.xjz.reflection.Person");
Field[] declaredFields = personCls.getDeclaredFields();
for (Field declaredField : declaredFields) {
System.out.println("本类中所有的属性=" + declaredField.getName()
+ " 该属性的修饰符值=" + declaredField.getModifiers()
+ " 该属性的类型=" + declaredField.getType());
}
Method[] declaredMethods = personCls.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
System.out.println("本类中所有方法=" + declaredMethod.getName()
+ " 该方法的访问修饰符值=" + declaredMethod.getModifiers()
+ " 该方法返回类型=" + declaredMethod.getReturnType());
Class<?>[] parameterTypes = declaredMethod.getParameterTypes();
for (Class<?> parameterType : parameterTypes) {
System.out.println("该方法的形参类型=" + parameterType);
}
}
Constructor<?>[] declaredConstructors = personCls.getDeclaredConstructors();
for (Constructor<?> declaredConstructor : declaredConstructors) {
System.out.println("==============================================");
System.out.println("本类中所有构造器=" + declaredConstructor.getName());
Class<?>[] parameterTypes = declaredConstructor.getParameterTypes();
for (Class<?> parameterType : parameterTypes) {
System.out.println("该构造器的形参类型=" + parameterType);
}
}
}
@Test
public void api_01() throws ClassNotFoundException {
Class<?> personCls = Class.forName("com.xjz.reflection.Person");
System.out.println(personCls.getName());
System.out.println(personCls.getSimpleName());
Field[] fields = personCls.getFields();
for (Field field : fields) {
System.out.println("本类以及父类的属性=" + field.getName());
}
Field[] declaredFields = personCls.getDeclaredFields();
for (Field declaredField : declaredFields) {
System.out.println("本类中所有的属性=" + declaredField.getName());
}
Method[] methods = personCls.getMethods();
for (Method method : methods) {
System.out.println("本类以及父类的方法=" + method.getName());
}
Method[] declaredMethods = personCls.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
System.out.println("本类中所有方法=" + declaredMethod.getName());
}
Constructor<?>[] constructors = personCls.getConstructors();
for (Constructor<?> constructor : constructors) {
System.out.println("本类的构造器=" + constructor.getName());
}
Constructor<?>[] declaredConstructors = personCls.getDeclaredConstructors();
for (Constructor<?> declaredConstructor : declaredConstructors) {
System.out.println("本类中所有构造器=" + declaredConstructor.getName());
}
System.out.println(personCls.getPackage());
Class<?> superclass = personCls.getSuperclass();
System.out.println("父类的 class对象=" + superclass);
Class<?>[] interfaces = personCls.getInterfaces();
for (Class<?> anInterface : interfaces) {
System.out.println("接口信息=" + anInterface);
}
Annotation[] annotations = personCls.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println("注解信息=" + annotation);
}
}
}
class A {
public String hobby;
public void hi(){
}
public A(){}
public A(String name){
}
}
interface IA{
}
interface IB{
}
@Deprecated
class Person extends A implements IA,IB{
public String name;
protected static int age;
String job;
private double sal;
public Person(){
}
public Person(String name){
}
public Person(String name,int age){
}
public void m1(String name,int age,double sal){
}
protected String m2(){
return null;
}
void m3(){
}
private void m4(){
}
}
6. 通过反射创建对象
- 测试 1:通过反射创建某类的对象,要求该类中必须有 public 的无参构造
- 测试 2:通过调用某个特定构造器的方式,实现创建某类的对象
package com.xjz.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ReflecCreateInstance {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class<?> userClass = Class.forName("com.xjz.reflection.User");
Object o = userClass.newInstance();
System.out.println(o);
Constructor<?> constructor = userClass.getConstructor(String.class);
Object xjz = constructor.newInstance("xjz");
System.out.println("xjz=" + xjz);
Constructor<?> constructor2 = userClass.getDeclaredConstructor(int.class, String.class);
constructor2.setAccessible(true);
Object user2 = constructor2.newInstance(100, "张杰");
System.out.println("user2=" + user2);
}
}
class User {
private int age = 10;
private String name = "xjz_2002";
public User() {
}
public User(String name) {
this.name = name;
}
private User(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "User[age" + age + ", name=" + name + ']';
}
}
7. 通过反射访问类中的成员
7.1 访问属性 ReflecAccessProperty.java
package com.xjz.reflection;
import java.lang.reflect.Field;
public class ReflecAccessProperty {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
Class<?> stuClass = Class.forName("com.xjz.reflection.Student");
Object o = stuClass.newInstance();
System.out.println(o.getClass());
Field age = stuClass.getField("age");
age.set(o,21);
System.out.println(o);
System.out.println(age.get(o));
Field name = stuClass.getDeclaredField("name");
name.setAccessible(true);
name.set(null,"老徐");
System.out.println(o);
System.out.println(name.get(o));
System.out.println(name.get(null));
}
}
class Student {
public int age;
private static String name;
public Student() {
}
@Override
public String toString() {
return "Student[age=" + age + ",name=" + name + ']';
}
}
7.2 访问方法 ReflecAccessMethod.java
package com.xjz.reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflecAccessMethod {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class<?> bossCls = Class.forName("com.xjz.reflection.Boss");
Object o = bossCls.newInstance();
Method hi = bossCls.getDeclaredMethod("hi", String.class);
hi.invoke(o,"张国荣");
Method say = bossCls.getDeclaredMethod("say", int.class, String.class, char.class);
say.setAccessible(true);
System.out.println(say.invoke(o,21,"xjz",'男'));
System.out.println(say.invoke(null,22,"tom",'女'));
Object reVal = say.invoke(null, 300, "王五", '男');
System.out.println("reVal 的运行类型=" + reVal.getClass());
Method m1 = bossCls.getDeclaredMethod("m1");
Object reVal2 = m1.invoke(o);
System.out.println("reVal2 =运行类型=" + reVal2.getClass());
}
}
class Monster {
}
class Boss {
public int age;
private static String name;
public Boss() {
}
public Monster m1() {
return new Monster();
}
private static String say(int n, String s, char c) {
return n + " " + s + " " + c;
}
public void hi(String s) {
System.out.println("hi " + s);
}
}
8. 本章作业
package com.xjz.homework;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Homework01 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class<PrivateTest> privateTestClass = PrivateTest.class;
PrivateTest privateTestObj = privateTestClass.newInstance();
Field name = privateTestClass.getDeclaredField("name");
name.setAccessible(true);
name.set(privateTestObj,"xjz");
Method getName = privateTestClass.getMethod("getName");
Object invoke = getName.invoke(privateTestObj);
System.out.println("name属性值=" + invoke);
}
}
class PrivateTest {
private String name = "hellokitty";
public String getName(){
return name;
}
}
package com.xjz.homework;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Homework02 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class<?> fileClass = Class.forName("java.io.File");
Constructor<?>[] declaredConstructors = fileClass.getDeclaredConstructors();
for (Constructor<?> declaredConstructor : declaredConstructors) {
System.out.println("File的类所有构造器=" + declaredConstructor);
}
Constructor<?> constructor = fileClass.getConstructor(String.class);
String fileAllPath = "d:\\mynew.txt";
Object file = constructor.newInstance(fileAllPath);
Method createNewFile = fileClass.getMethod("createNewFile");
createNewFile.invoke(file);
System.out.println(file.getClass());
System.out.println("创建文件成功" + fileAllPath);
}
}