Java dynamically loads classes from the jar file

Source: Internet
Author: User

Because of the need for development, you need to dynamically load classes based on the configuration, so simply test the Java dynamic load class

Defining interfaces
Package Loader;public interface Helloiface {public String hello (); Public String Sayhi ();}

Implementing interfaces

Implement this interface in other plug-in classes and export it as a jar, such as D:/tmp/test.jar

Package Loader;public class Helloimpl implements helloiface{@Overridepublic String Hello () {return "Hello,java World";} @Overridepublic String Sayhi () {return "Hi,java World";}}

Dynamic Load Class
Import Java.net.url;import Java.net.urlclassloader;import loader. Helloiface;public class Main {public static void Main (string[] args) {String ClassPath = "loader. Helloimpl ";//The Class name of the class that needs to be loaded in the jar string jarpath =" File:///D:/tmp/test.jar ";//The URLClassLoader of the file where the jar is located cl;try {// Get a class loader from the jar file CL = new URLClassLoader (new url[] {new URL (Jarpath)});//load from loader classclass<?> c = Cl.loadclass (c Lasspath);//Instantiate an object from class Helloiface Impl = (helloiface) c.newinstance ();//Call the class method in the Jar System.out.println (Impl.hello ()); System.out.println (Impl.sayhi ());} catch (Exception e) {e.printstacktrace ();}}}


Java dynamically loads classes from the jar file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.