This article mainly introduces the relevant information about the implementation code of java dynamic loading. The main purpose of dynamically loading Java classes is not to change the main program code. By modifying the configuration file, you can operate different objects to perform different functions. Friends in need You can refer to the implementation code of
java dynamic loading
The meaning and purpose of Java dynamic loading class:
Java Dynamic loading of classes is mainly to avoid changing the main program code. By modifying the configuration file, you can operate different objects to perform different functions. It is mainly beneficial to the expansion of the system. For example, when I want to change a function, I only need to make a class and then write the corresponding function. The new function can be used through the configuration file. There is no need to modify anywhere in the system. I only need to add a class. ; Fully realized loose coupling. Satisfies the open-closed principle (closed for modification, open for addition or deletion);
public abstract class AbstractAction { public abstract String action(); } public class TestAction extends AbstractAction{ public String action() { System.out.println("I am working ! "); return "this ActionTest class"; } }
String s = "file://D:\Style.jar";***//jar所在的文件的URL* URL url = new URL(s); URLClassLoader myClassLoader = new URLClassLoader(new URL[] { url }, Thread.currentThread() .getContextClassLoader()); Class<? extends AbstractAction> myClass = (Class<? extends AbstractAction>) myClassLoader.loadClass("com.java.jarloader.TestAction"); AbstractAction action = (AbstractAction) myClass.newInstance(); String str = action.action(); System.out.println(str);
The above is the detailed content of How to implement dynamically loaded code examples in Java. For more information, please follow other related articles on the PHP Chinese website!