当前位置:网站首页>通过反射执行任意类的任意方法
通过反射执行任意类的任意方法
2022-07-02 09:43:00 【牧歌ing】
通过反射执行任意类的任意方法
Java的反射机制:在程序运行的时候可以调用
Class aClass = Class.forName(className);
Object obj = aClass.newInstance();等反射的API获取任何类的内部信息(字段、方法等),并且能操作这些内部信息
我们在调用Class.forName(className)的时候,会在堆中加载一个Class类型的对象,这个对象就是传入的className,也就是说我们可以通过这个Class类型的对象操作className的方法、属性等。
1、项目结构

2、用来演示的两个类
package com.zhou.reflect.pet;
/** * @author DELL * @version 1.0 * @Description * @date 2022/5/24 16:58 */
public class Cat {
public void sound(){
System.out.println("喵喵喵...");
}
}
package com.zhou.reflect.pet;
/** * @author DELL * @version 1.0 * @Description * @date 2022/5/24 16:54 */
public class Dog {
public void sound(){
System.out.println("汪汪汪...");
}
}
3、properties
# 这里配置需要调用的类路径
className=com.zhou.reflect.pet.Cat
# 需要调用的方法
methodName=sound
4、主要实现
package com.zhou.reflect;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.lang.reflect.Method;
import java.util.Properties;
/** * @author DELL * @version 1.0 * @Description * @date 2022/5/24 17:05 */
public class ReflectFactory {
public static void main(String[] args) {
/* * 需求:不修改这个类的代码,自动调用任意类的任意方法 * */
try {
//1、得到resource目录下的properties
ClassPathResource classPathResource = new ClassPathResource("/application.properties");
Properties properties = PropertiesLoaderUtils.loadProperties(classPathResource);
//2、获取配置文件的内容
String className = properties.getProperty("className");
String methodName = properties.getProperty("methodName");
//3、得到类的对象
Class aClass = Class.forName(className);
//4、初始化这个对象
Object obj = aClass.newInstance();
//5、得到类的方法
Method method = aClass.getMethod(methodName);
//6、执行这个方法
method.invoke(obj);
} catch (Exception ex) {
System.out.println(ex);
}
}
}
5、执行结果
配置文件中配置的调用Cat的sound方法,输出结果是“喵喵喵…”
配置文件中配置的调用dog的sound方法,输出结果是“汪汪汪…”
边栏推荐
- Leetcode - Sword finger offer 37, 38
- Input a three digit number and output its single digit, ten digit and hundred digit.
- LeetCode—剑指 Offer 59 - I、59 - II
- Drools executes the specified rule
- (C language) 3 small Codes: 1+2+3+ · · +100=? And judge whether a year is a leap year or a normal year? And calculate the circumference and area of the circle?
- Multiply LCA (nearest common ancestor)
- 深拷贝 事件总线
- Leetcode - Sword finger offer 59 - I, 59 - II
- Day12 control flow if switch while do While guessing numbers game
- Experiment of connecting mobile phone hotspot based on Arduino and esp8266 (successful)
猜你喜欢

Find the common ancestor of any two numbers in a binary tree

MySQL and PostgreSQL methods to grab slow SQL

线性DP AcWing 896. 最长上升子序列 II

Distributed machine learning framework and high-dimensional real-time recommendation system

AAAI 2022 | Peking University & Ali Dharma Institute: pruning and compression of pre training language model based on comparative learning

计数类DP AcWing 900. 整数划分

(C language) 3 small Codes: 1+2+3+ · · +100=? And judge whether a year is a leap year or a normal year? And calculate the circumference and area of the circle?
![[old horse of industrial control] detailed explanation of Siemens PLC TCP protocol](/img/13/9002244555ebe8a61660c2506993fa.png)
[old horse of industrial control] detailed explanation of Siemens PLC TCP protocol

染色法判定二分图 AcWing 860. 染色法判定二分图

Win10 system OmniPeek wireless packet capturing network card driver failed to install due to digital signature problem solution
随机推荐
CDA data analysis -- Introduction and use of aarrr growth model
H5 to app
IPhone 6 plus is listed in Apple's "retro products" list
Anti shake throttle
String palindrome hash template question o (1) judge whether the string is palindrome
Deep understanding of P-R curve, ROC and AUC
线性DP AcWing 896. 最长上升子序列 II
Map和Set
The second composition template of postgraduate entrance examination English / chart composition, English chart composition is enough
Find the factorial of a positive integer within 16, that is, the class of n (0= < n < =16). Enter 1111 to exit.
kubenetes中port、targetPort、nodePort、containerPort的区别与联系
Go学习笔记—基于Go的进程间通信
AI mid stage technology research
线性DP AcWing 898. 数字三角形
Leetcode739 daily temperature
深拷貝 事件總線
Floyd AcWing 854. Floyd求最短路
LeetCode—剑指 Offer 51. 数组中的逆序对
Tas (file d'attente prioritaire)
Does C language srand need to reseed? Should srand be placed in the loop? Pseudo random function Rand