Skip to content

Instantly share code, notes, and snippets.

@xudifsd
Created December 14, 2013 08:17
Show Gist options
  • Save xudifsd/7956841 to your computer and use it in GitHub Desktop.
Save xudifsd/7956841 to your computer and use it in GitHub Desktop.
class loader demo
import java.io.*;
public class ClassLoaderTest {
public static void main(String[] args) throws Exception {
ClassLoader myLoader = new ClassLoader() {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
try {
String fileName = "foo/" + name.replace('.', '/') + ".class";
System.out.println(fileName);
InputStream is = getClass().getResourceAsStream(fileName);
if (is == null) {
System.out.println("'is' is null when loading " + fileName);
return super.loadClass(name);
}
byte[] b = new byte[is.available()];
is.read(b);
return defineClass(name, b, 0, b.length);
} catch (IOException e) {
throw new ClassNotFoundException(name);
}
}
};
Object obj = myLoader.loadClass("pack.Main").newInstance();
System.out.println("obj.getClass is " + obj.getClass());
System.out.println(obj.hashCode());
}
}
package pack;
public class Main {
/* replace filename '.' with '/' and compile it */
public int hashCode() {
System.out.println("in Main");
return 1024;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment