java 动态load class 的方法之二:从网络动态加载一个类

摘要: 前面测试过最基本的从本地文件动态加载一个类 最基本的java 动态加载类方法, 今天测试一个从网络上动态加载一个类的方法。

前面测试过最基本的从本地文件动态加载一个类 最基本的java 动态加载类方法, 今天测试一个从网络上动态加载一个类的方法, 最重要的就是利用:URLClassLoader

假设有这样的一个类:

package com.yihaomen;

public class ClassLoaderInput {
	public void printString() {
		System.out.println("Hello world from the loaded class !!!");
	}
}


这个类被最终被打包到了test.jar 中

第一种方法动态调用这个jar 包中的这个类中的方法
public class URLClassLoaderTest {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		
		// Getting the jar URL which contains target class
		URL[] classLoaderUrls = new URL[]{new URL("file:///c:/test.jar")};
		
		// Create a new URLClassLoader 
		URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls);
		
		// Load the target class
        Class beanClass = urlClassLoader.loadClass("com.yihaomen.ClassLoaderInput");
        
        // Create a new instance from the loaded class
        Constructor constructor = beanClass.getConstructor();
        Object beanObj = constructor.newInstance();
        
        // Getting a method from the loaded class and invoke it
        Method method = beanClass.getMethod("printString");
        method.invoke(beanObj);

	}

}


还有一种方法, 通过getResourceAsStream 方法来实现

public class JavaClassLoaderTest extends ClassLoader {

	public static void main(String args[]) throws Exception {
		JavaClassLoaderTest javaClassLoader = new JavaClassLoaderTest();
		javaClassLoader.load();

	}

	public void load() throws Exception {

		// create FileInputStream object
		InputStream fileInputStream = this.getClass().getClassLoader().getResourceAsStream("ClassLoaderInput.class");

		/*
		 * Create byte array large enough to hold the content of the file. Use
		 * fileInputStream.available() to determine size of the file in bytes.
		 */
		byte rawBytes[] = new byte[fileInputStream.available()];

		/*
		 * To read content of the file in byte array, use int read(byte[]
		 * byteArray) method of java FileInputStream class.
		 */
		fileInputStream.read(rawBytes);

		// Load the target class
		Class regeneratedClass = this.defineClass(rawBytes, 0, rawBytes.length);

		// Getting a method from the loaded class and invoke it
		regeneratedClass.getMethod("printString", null).invoke(regeneratedClass.newInstance(), null);
	}

}

上一篇: java 动态load class 的方法之一
下一篇: Django request 获取全路径的方法
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号