Created
December 14, 2013 08:17
-
-
Save xudifsd/7956841 to your computer and use it in GitHub Desktop.
class loader demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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