(1-9-3) Java 反射 Reflect
·
目录
03. 异常1:ClassNotFoundException
04. 异常2:InstantiationException
05. 异常3:IllegalAccessException
1. 介绍反射与其作用
1.1 什么是反射

1.2 对比传统方式与反射方式
00. base

package com.imooc.reflect;
/**
* 四则运算接口
*/
public interface MathOperation {
public float operate(int a , int b);
}
package com.imooc.reflect;
/**
* 加法
*/
public class Addition implements MathOperation {
@Override
public float operate(int a , int b) {
System.out.println("执行加法运算");
return a + b;
}
}
package com.imooc.reflect;
/**
* 减法运算
*/
public class Subtraction implements MathOperation {
@Override
public float operate(int a, int b) {
System.out.println("执行减法运算");
return a - b;
}
}
01. 传统创建对象方式
public class ReflectSample {
/**
* 传统的创建对象方式
*/
public static void case1(){
Scanner scanner = new Scanner(System.in);
System.out.print("请输入计算类名:");
String op = scanner.next();
System.out.print("请输入a:");
int a = scanner.nextInt();
System.out.print("请输入b:");
int b = scanner.nextInt();
MathOperation mathOperation = null;
if(op.equals("Addition")){
mathOperation = new Addition();
}else if(op.equals("Subtraction")) {
mathOperation = new Subtraction();
}else if(op.equals("Multiplication")){
mathOperation = new Multiplication();
}else{
System.out.println("无效的计算类");
return;
}
float result = mathOperation.operate(a, b);
System.out.println(result);
}
public static void main(String[] args) {
ReflectSample.case1();
}
}

02. 通过反射创建对象

package com.imooc.reflect;
import java.util.Scanner;
/**
* 初识反射的作用
*/
public class ReflectSample {
/**
* 利用反射在运行时 动态创建对象
*/
public static void reflectDemo(){
Scanner scanner = new Scanner(System.in);
System.out.print("请输入计算类名:");
String op = scanner.next();
System.out.print("请输入a:");
int a = scanner.nextInt();
System.out.print("请输入b:");
int b = scanner.nextInt();
MathOperation mathOperation = null;
// 找到[包名(路径) + 类名]
// 在对其进行实例化
// 最后通过接口类型的变量接收
try {
mathOperation = (MathOperation)Class.forName("com.imooc.reflect." + op).newInstance();
} catch (Exception e) {
System.out.println("无效的计算");
e.printStackTrace();
// 让程序中断
return;
}
float result = mathOperation.operate(a, b);
System.out.println(result);
}
public static void main(String[] args) {
ReflectSample.reflectDemo();
}
}
03. 直观对比

2. 反射的四个核心类
2.1 Class 类
(1). Class 类概述 与 核心方法


(2) Class.forName()
00. base & 效果

01. Employee
package com.phdvb.reflect.entity;
import java.util.Date;
public class Employee {
private Integer empno;
private String ename;
private String job;
private Integer mgr;
private Date hiredate;
private Float sal;
private Float comm;
private Integer deptno;
public Employee() {
System.out.println("Employee Constructor 已经执行!");
}
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public int getMgr() {
return mgr;
}
public void setMgr(Integer mgr) {
this.mgr = mgr;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public float getSal() {
return sal;
}
public void setSal(Float sal) {
this.sal = sal;
}
public float getComm() {
return comm;
}
public void setComm(Float comm) {
this.comm = comm;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
}
02. ClassDemo
package com.phdvb.reflect;
import com.phdvb.reflect.entity.Employee;
public class ClassDemo {
public static void main(String[] args) {
// Class.forName() 方法将指定的类加载到 jvm
// 并返回 class 对象
try {
Class empClass = Class.forName("com.phdvb.reflect.entity.Employee");
System.out.println("Employee类 已经加载到了 jvm !");
// 得到 employ 这个类的对象
Employee emp = (Employee)empClass.newInstance();
System.out.println(emp);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
03. 异常1:ClassNotFoundException

04. 异常2:InstantiationException

05. 异常3:IllegalAccessException

2.2 Constructor 构造方法
(1)两个重要方法

(2)案例实现
00. base & 效果


01. Employee
package com.phdvb.reflect.entity;
import java.util.Date;
// 经过abstract 修饰的类无法实例化
//public abstract class Employee {
public class Employee {
private Integer empno;
private String ename;
private String job;
private Integer mgr;
private Date hiredate;
private Float sal;
private Float comm;
private Integer deptno;
private Employee() {
// public Employee() {
System.out.println("Employee Constructor 已经执行!");
}
public Employee(Integer empno, String ename, String job, Integer mgr, Date hiredate, Float sal, Float comm, Integer deptno) {
this.ename = ename;
this.job = job;
this.empno = empno;
this.mgr = mgr;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
this.deptno = deptno;
System.out.println("Employee带参构造方法已被执行");
}
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public int getMgr() {
return mgr;
}
public void setMgr(Integer mgr) {
this.mgr = mgr;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public float getSal() {
return sal;
}
public void setSal(Float sal) {
this.sal = sal;
}
public float getComm() {
return comm;
}
public void setComm(Float comm) {
this.comm = comm;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
}
02.ConstructorDemo
package com.phdvb.reflect;
import com.phdvb.reflect.entity.Employee;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 利用带参构造方法创建对象
*/
public class ConstructorDemo {
public static void main(String[] args) {
try {
Class employeeClass = Class.forName("com.phdvb.reflect.entity.Employee");
Constructor constructor = employeeClass.getConstructor(new Class[]{
Integer.class, String.class, String.class, Integer.class, Date.class, Float.class, Float.class, Integer.class
});
Employee employee = (Employee) constructor.newInstance(new Object[]{
11111, "剖好的VB", "教师", 8888,
new SimpleDateFormat("yyyy-MM-dd").parse("2025-08-06"),
5500f, 3500f, 20
});
System.out.println(employee);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
//没有找到与之对应格式的方法
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
//当被调用的方法的内部抛出了异常而没有被捕获时
e.printStackTrace();
}catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
2.3 Method 方法类
(1)Method概述 与 核心方法


(2)案例实现
00. base & 效果


01. Employee
package com.phdvb.reflect.entity;
import java.util.Date;
// 经过abstract 修饰的类无法实例化
//public abstract class Employee {
public class Employee {
private Integer empno;
private String ename;
private String job;
private Integer mgr;
private Date hiredate;
private Float sal;
private Float comm;
private Integer deptno;
private Employee() {
// public Employee() {
System.out.println("Employee Constructor 已经执行!");
}
public Employee(Integer empno, String ename, String job, Integer mgr, Date hiredate, Float sal, Float comm, Integer deptno) {
this.ename = ename;
this.job = job;
this.empno = empno;
this.mgr = mgr;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
this.deptno = deptno;
System.out.println("Employee带参构造方法已被执行");
}
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public int getMgr() {
return mgr;
}
public void setMgr(Integer mgr) {
this.mgr = mgr;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public float getSal() {
return sal;
}
public void setSal(Float sal) {
this.sal = sal;
}
public float getComm() {
return comm;
}
public void setComm(Float comm) {
this.comm = comm;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
public Employee updateSal(Float sal) {
float preSal = this.sal;
this.sal = this.sal + sal;
System.out.println(this.ename + "的薪资由" + preSal +", 调整到了" + this.sal);
return this;
}
}
02. MethodDemo
package com.phdvb.reflect;
import com.phdvb.reflect.entity.Employee;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MethodDemo {
public static void main(String[] args) {
try {
Class empClass = Class.forName("com.phdvb.reflect.entity.Employee");
Constructor constructor = empClass.getConstructor(new Class[]{
Integer.class, String.class, String.class, Integer.class, Date.class, Float.class, Float.class, Integer.class
});
Employee employee = (Employee) constructor.newInstance(new Object[]{
11111, "剖好的VB", "教师", 8888,
new SimpleDateFormat("yyyy-MM-dd").parse("2025-08-06"),
5500f, 3500f, 20
});
System.out.println("pre-Emp: " + employee);
System.out.println("pre-Emp: emp-Sal" + employee.getSal());
Method updateSalMethod = empClass.getMethod("updateSal", new Class[]{Float.class});
Employee employee1 = (Employee) updateSalMethod.invoke(employee, new Object[]{1500f});
System.out.println("post-Emp:" + employee1);
System.out.println("post-Emp: emp-Sal" + employee1.getSal());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (ParseException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
2.4 Field 成员变量类
(1) Field 概述 与 核心方法


(2) 案例实现
00.base & 效果


01. FieldDemo
package com.phdvb.reflect;
import com.phdvb.reflect.entity.Employee;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 通过 Field 对成员变量 赋值与取值
*/
public class FieldDemo {
public static void main(String[] args) {
try {
Class empClass = Class.forName("com.phdvb.reflect.entity.Employee");
Constructor constructor = empClass.getConstructor(new Class[]{
Integer.class, String.class, String.class, Integer.class, Date.class, Float.class, Float.class, Integer.class
});
Employee employee = (Employee) constructor.newInstance(new Object[]{
11111, "剖好的VB", "教师", 8888,
new SimpleDateFormat("yyyy-MM-dd").parse("2025-08-06"),
5500f, 3500f, 20
});
Field enameField = empClass.getField("ename");
String ename = (String) enameField.get(employee);
System.out.println("获取员工原先的名称:" + ename);
enameField.set(employee, "phdvb");
String ename1 = (String) enameField.get(employee);
System.out.println("获取完善后员工的名称:" + ename1);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (ParseException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
}
2.5 getDeclared方法
(1)getDeclared 概述

(2) 具体案例
00. base & 效果


01. Employee

02. getDeclaredDemo
package com.phdvb.reflect;
import com.phdvb.reflect.entity.Employee;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class getDeclaredDemo {
public static void main(String[] args) {
try {
Class empClass = Class.forName("com.phdvb.reflect.entity.Employee");
Constructor constructor = empClass.getConstructor(new Class[]{
Integer.class, String.class, String.class, Integer.class, Date.class, Float.class, Float.class, Integer.class
});
Employee employee = (Employee) constructor.newInstance(new Object[]{
11111, "剖好的VB", "教师", 8888,
new SimpleDateFormat("yyyy-MM-dd").parse("2025-08-06"),
5500f, 3500f, 20
});
Field[] fields = empClass.getDeclaredFields();
for (Field field : fields) {
System.out.print(field.getName() + " | ");
//empno | ename | job | mgr | hiredate | sal | comm | deptno |
if (field.getModifiers() == 1) { // 属性被 public 所修饰
Object value = field.get(employee);
System.out.println(field.getName() + ":" + value);
}else if(field.getModifiers() == 2) { // 属性被 private 修饰
String methodName = "get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
System.out.println("methodName:" + methodName);
Method method = empClass.getMethod(methodName);
Object ret = method.invoke(employee);
System.out.println(field.getName() + ":" + ret);
}
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
3. 反射在I18N项目中的应用
3.1 目录

3.2 I18N
package com.i18n.reflect;
public interface I18N {
public String say();
}
3.3 En
package com.i18n.reflect;
public class En implements I18N{
@Override
public String say() {
return "Life is endless, and the struggle is endless.";
}
}
3.4 Zhcn
package com.i18n.reflect;
public class Zhcn implements I18N{
@Override
public String say() {
return "生命不息,奋斗不止";
}
}
3.5 config.properties
#language=com.i18n.reflect.Zhcn
language=com.i18n.reflect.En
3.6 Application
package com.i18n.reflect;
import java.io.FileInputStream;
import java.net.URLDecoder;
import java.util.Properties;
public class Application {
public static void say(){
Properties properties = new Properties();
String configPath = Application.class.getResource("/config.properties").getPath();
System.out.println("configPath1: " + configPath);
//configPath1: /D:/s_java/se/9-3reflect/math/out/production/math/config.properties
try {
configPath = new URLDecoder().decode(configPath, "UTF-8");
System.out.println("configPath2: " + configPath);
//configPath2: /D:/s_java/se/9-3reflect/math/out/production/math/config.properties
properties.load(new FileInputStream(configPath));
String language = properties.getProperty("language");
System.out.println("language: " + language);
//language: com.i18n.reflect.Zhcn
I18N i18N = (I18N) Class.forName(language).newInstance();
System.out.println("i18N: " + i18N);
//i18N: com.i18n.reflect.Zhcn@4554617c
System.out.println(i18N.say());
//生命不息,奋斗不止
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
Application.say();
}
}
3.7 实现效果


更多推荐
所有评论(0)