public class Hello {
{
System.out.println("Empty block initial");
}
static {
System.out.println("Static initial");
}
public Hello() {
System.out.println("Hello URLClassLoader!");
}
}
import java.io.*;
import java.lang.reflect.Method;
public class LoaderTest {
public static byte[] getClassByteCode(String classPath) throws FileNotFoundException {
InputStream is = new FileInputStream(classPath);
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
int ch;
byte data[] = null;
try {
while ((ch = is.read()) != -1) {
bytestream.write(ch);
}
data = bytestream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bytestream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return data;
}
public static void main(String[] args) throws Exception {
byte[] code = getClassByteCode("E:/server/Hello.class");
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class);
defineClass.setAccessible(true);
Class hello = (Class)defineClass.invoke(ClassLoader.getSystemClassLoader(), "Hello", code, 0, code.length );
hello.newInstance();
}
}
static final class TransletClassLoader extends ClassLoader {
TransletClassLoader(ClassLoader parent) {
super(parent);
_loadedExternalExtensionFunctions = null;
}
TransletClassLoader(ClassLoader parent, Map<String, Class<?>> mapEF) {
super(parent);
_loadedExternalExtensionFunctions = mapEF;
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
Class<?> ret = null;
// The _loadedExternalExtensionFunctions will be empty when the
// SecurityManager is not set and the FSP is turned off
if (_loadedExternalExtensionFunctions != null) {
ret = _loadedExternalExtensionFunctions.get(name);
}
if (ret == null) {
ret = super.loadClass(name);
}
return ret;
}
/**
* Access to final protected superclass member from outer class.
*/
Class<?> defineClass(final byte[] b) {
return defineClass(null, b, 0, b.length);
}
}