Java How to load classes and jar packages through the class loader

Source: Internet
Author: User

Scene:

Put the class files and jars in the project into the D:\loader\terry\codex directory, how to get the project to load and use these classes in code way.


Scenario: Using URLClassLoader constructs D:\loader\terry\codex the class loader under this path, and uses these classes to instantiate through the Java reflection mechanism


Example:


Helloworld.java:

Package terry.codex;

/**
 * @ Writer: Yh.zeng
 * @ Write Time: 2017-12-3 pm 2:29:57
 * @ file Description: Todo/
 public
class HelloWorld {
	
	public void SayHello () {
		System.out.println ("HelloWorld. ");
	}

}


Test.java:

Import Java.io.File;
Import Java.lang.reflect.Method;
Import Java.net.URL;
Import Java.net.URLClassLoader;


/**
 * @ Writer: Yh.zeng
 * @ Write Time: 2017-12-3 pm 2:26:59
 * @ file Description: Todo/
 public
class Test {

	public static void Main (string args[]) {
        string fileurlstring = new File ("D:\\loader"). Touri (). toString ();
        fileurlstring = Fileurlstring.replaceall ("!/", "%21/");
		try {
			ClassLoader ClassLoader = new URLClassLoader (new Url[]{new URL (fileurlstring)});
			Class Helloworldclazz = Classloader.loadclass ("Terry.codex.HelloWorld");
			Object HelloWorld = Helloworldclazz.newinstance ();
			Method method = Helloworld.getclass (). GetMethod ("SayHello", null);
			Method.invoke (HelloWorld, null);
		catch (Exception E1) {
			//TODO auto-generated catch block
			e1.printstacktrace ();
		}
	}
}


Demo See: Https://github.com/zengyh/CodeLibary/blob/master/src/clazzloader/UrlClassLoaderTest.java



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.