当前位置: 技术问答>java相关
怎么动态加载class
来源: 互联网 发布时间:2017-03-22
本文导语: 如题 | import java.io.*; import java.util.*; import java.util.jar.*; import java.lang.Exception.*; import java.util.zip.*; public class myClassLoader extends ClassLoader { public synchronized Class loadClass(String className,String ja...
如题
|
import java.io.*;
import java.util.*;
import java.util.jar.*;
import java.lang.Exception.*;
import java.util.zip.*;
public class myClassLoader extends ClassLoader {
public synchronized Class loadClass(String className,String jarpath) throws ClassNotFoundException{
Class result = null;
byte[] classData = null;
try{
classData = getByteArrayFromJarFile(className,jarpath);
result = defineClass(className, classData, 0, classData.length);
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
private byte[] getByteArrayFromJarFile(String className,String jarpath){
int len;
byte buffer[] = new byte[1024];
JarFile jarFile = null;
try{
jarFile = new JarFile(jarpath);
}catch(Exception ex){
}
className = className.replace('.','/');
try{
ZipEntry zipEntry = jarFile.getEntry(className+".class");
if(zipEntry!=null){
try{
InputStream inputStream = jarFile.getInputStream(zipEntry);
int arrayLength = inputStream.available();
byte[] bytes = new byte[arrayLength];
int pos = 0;
while (true) {
int n = inputStream.read(bytes, pos,arrayLength - pos);
if (n
import java.util.*;
import java.util.jar.*;
import java.lang.Exception.*;
import java.util.zip.*;
public class myClassLoader extends ClassLoader {
public synchronized Class loadClass(String className,String jarpath) throws ClassNotFoundException{
Class result = null;
byte[] classData = null;
try{
classData = getByteArrayFromJarFile(className,jarpath);
result = defineClass(className, classData, 0, classData.length);
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
private byte[] getByteArrayFromJarFile(String className,String jarpath){
int len;
byte buffer[] = new byte[1024];
JarFile jarFile = null;
try{
jarFile = new JarFile(jarpath);
}catch(Exception ex){
}
className = className.replace('.','/');
try{
ZipEntry zipEntry = jarFile.getEntry(className+".class");
if(zipEntry!=null){
try{
InputStream inputStream = jarFile.getInputStream(zipEntry);
int arrayLength = inputStream.available();
byte[] bytes = new byte[arrayLength];
int pos = 0;
while (true) {
int n = inputStream.read(bytes, pos,arrayLength - pos);
if (n