Home> Java> javaTutorial> body text

Java reflection case (don't miss it)

藏色散人
Release: 2020-06-12 13:25:37
forward
1850 people have browsed it

The following is a Java reflection case introduced by thejava learningtutorial column. I hope it will be helpful to friends in need!

Java reflection case (don't miss it)

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

Java reflection case (dont miss it)

className=Student methodName=sleep
Copy after login

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); } }
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!