Home > Java > javaTutorial > body text

How to implement dynamically loaded code examples in Java

黄舟
Release: 2017-07-26 15:12:21
Original
2386 people have browsed it

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


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

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
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!