java 动态load class 的方法之二:从网络动态加载一个类
By:Roy.LiuLast updated:2014-11-19
前面测试过最基本的从本地文件动态加载一个类 最基本的java 动态加载类方法, 今天测试一个从网络上动态加载一个类的方法, 最重要的就是利用:URLClassLoader
假设有这样的一个类:
这个类被最终被打包到了test.jar 中
第一种方法动态调用这个jar 包中的这个类中的方法
还有一种方法, 通过getResourceAsStream 方法来实现
假设有这样的一个类:
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);
}
}
From:一号门
Previous:java 动态load class 的方法之一

COMMENTS