The following is a Java reflection case introduced by the java learning tutorial column. I hope it will be helpful to friends in need!
Java reflection case
Requirements
Write a "framework" that cannot change any code of this class Under the premise, we can help us create objects of any class and execute any method
Use
Configuration file
Reflection
Steps
Define the full class name of the object to be created and the method to be executed in the configuration file
Load and read the configuration file in the program
Use reflection technology to load class files into memory
Create object
Execution method
Configuration file
className=Student methodName=sleep
code
import java.io.InputStream; import java.lang.reflect.Method; import java.util.Properties; /** * @author tanglei * @date 2020/6/11 3:10 下午 */ public class ReflectTest { public static void main(String[] args) throws Exception { Student s = new Student(); Properties pro = new Properties(); //获取配置文件的路径 ClassLoader classLoader = ReflectTest.class.getClassLoader(); InputStream is = classLoader.getResourceAsStream("pro.properties"); pro.load(is); String className = pro.getProperty("className"); String methodName = pro.getProperty("methodName"); //加载类进内存 Class cla = Class.forName(className); Object obj = cla.newInstance(); //加载方法进内存 Method method = cla.getMethod(methodName); method.invoke(obj); } }
The above is the detailed content of Java reflection case (don’t miss it). For more information, please follow other related articles on the PHP Chinese website!