当前位置:网站首页>通过反射执行任意类的任意方法
通过反射执行任意类的任意方法
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方法,输出结果是“汪汪汪…”
边栏推荐
- Deep Copy Event bus
- Bom Dom
- Is the neural network (pinn) with embedded physical knowledge a pit?
- Introduction to CPU instruction set
- The blink code based on Arduino and esp8266 runs successfully (including error analysis)
- What is the relationship between NFT and metauniverse? How to view the market? The future market trend of NFT
- 线性DP AcWing 898. 数字三角形
- drools动态增加、修改、删除规则
- arcgis js 4.x 地图中加入图片
- Lekao: 22 year first-class fire engineer "technical practice" knowledge points
猜你喜欢
[ybtoj advanced training guidance] judgment overflow [error]
Enhance network security of kubernetes with cilium
Less than three months after the programmer was hired, the boss wanted to launch the app within one month. If he was dissatisfied, he was dismissed immediately
js 迭代器 生成器 异步代码处理 promise+生成器 -> await/async
2.7 binary tree, post order traversal - [FBI tree]
Jenkins voucher management
寻找二叉树中任意两个数的公共祖先
The programmer and the female nurse went on a blind date and spent 360. He packed leftovers and was stunned when he received wechat at night
Embedded Software Engineer career planning
1380. Lucky numbers in the matrix [two-dimensional array, matrix]
随机推荐
防抖 节流
Win10 system OmniPeek wireless packet capturing network card driver failed to install due to digital signature problem solution
排序---
Experiment of connecting mobile phone hotspot based on Arduino and esp8266 (successful)
Leetcode209 subarray with the smallest length
Does C language srand need to reseed? Should srand be placed in the loop? Pseudo random function Rand
Performance tuning project case
CDA数据分析——AARRR增长模型的介绍、使用
Post request body content cannot be retrieved repeatedly
LeetCode—剑指 Offer 59 - I、59 - II
Calculate the maximum path sum of binary tree
[C language] Yang Hui triangle, customize the number of lines of the triangle
LeetCode—<动态规划专项>剑指 Offer 19、49、60
The differences and relationships among port, targetport, nodeport and containerport in kubenetes
Drools executes string rules or executes a rule file
CPU指令集介绍
Leetcode739 daily temperature
分布式机器学习框架与高维实时推荐系统
Leetcode - Sword finger offer 59 - I, 59 - II
Interview with meituan, a 34 year old programmer, was rejected: only those under the age of 30 who work hard and earn little overtime