import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
public class ClassLoaderTest extends ClassLoader{
static final String className ="C://Test.class";
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, IOException {
ClassLoaderTest clt = new ClassLoaderTest();
FileInputStream fis = new FileInputStream(className);
FileChannel fc = null;
if (fis != null) {
fc = fis.getChannel();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
WritableByteChannel wbc = Channels.newChannel(baos);
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
while (true) {
int i = fc.read(buffer);
if (i == 0 || i == -1) {
break;
}
buffer.flip();
wbc.write(buffer);
buffer.clear();
}
fis.close();
byte[] bytes = baos.toByteArray();
Class clz = clt.defineClass("Test", bytes, 0, bytes.length);
System.out.println(clz.getName());
Field[] fields = clz.getFields();
for(Field field: fields)
System.out.println(field.getName());
Method[] methods = clz.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
Class[] clis = clz.getInterfaces();
for (Class cli : clis) {
System.out.println(cli.getName());
}
fis.close();
baos.close();
}
}
转载于:https://my.oschina.net/jimyao/blog/648154