Test1.java:
package test;
import java.io.*;
import java.lang.reflect.*;
class AClassLoader extends ClassLoader {
public Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class klass = null;
try {
klass = findLoadedClass(name); //检查该类是否已经被装载。
if (klass != null) {
return klass;
}
byte[] bs = getClassBytes(name);//从一个特定的信息源寻找并读取该类的字节。
if (bs != null && bs.length > 0) {
klass = defineClass(name, bs, 0, bs.length);
}
if (klass == null) { //如果读取字节失败,则试图从JDK的系统API中寻找该类。
klass = findSystemClass(name);
}
if (resolve && klass != null) {
resolveClass(klass);
}
} catch (IOException e) {
throw new ClassNotFoundException(e.toString());
}
System.out.println("klass == " + klass);
return klass;
}
private byte[] getClassBytes(String className) throws IOException {
String path = System.getProperty("java.class.path") + File.separator;
path += className.replace('.', File.separatorChar) + ".class";
System.out.println(path);
FileInputStream fis = null;
try {
fis = new FileInputStream(path);
} catch (FileNotFoundException e) {
System.out.println(e);
return null; //如果查找失败,则放弃查找。捕捉这个异常主要是为了过滤JDK的系统API。
}
byte[] bs = new byte[fis.available()];
fis.read(bs);
return bs;
}
}
public class Test1 {
public static void main(String[] args) throws Exception{
AClassLoader loader = new AClassLoader();
Class c = loader.loadClass("test.A", false);
System.out.println(c);
Object o = c.newInstance();
System.out.println(o);
Method m = c.getMethod("print", java.lang.String.class);
m.invoke(o, "bitan");
}
}
A.java
package test;
public class A {
public void print(String str) {
System.out.println("嗨," + str + ", 你终于找到我了!");
}
public String toString() {
return "我是一个A对象!";
}
}
结果:
C:\test>javac -d .\bin .\src\*.java
C:\test>java -classpath .\bin test.Test1
.\bin\test\A.class
.\bin\java\lang\Object.class
java.io.FileNotFoundException: .\bin\java\lang\Object.class (系统找不到指定的路
径。)
klass == class java.lang.Object
klass == class test.A
class test.A
我是一个A对象!
.\bin\java\lang\String.class
java.io.FileNotFoundException: .\bin\java\lang\String.class (系统找不到指定的路
径。)
klass == class java.lang.String
.\bin\java\lang\System.class
java.io.FileNotFoundException: .\bin\java\lang\System.class (系统找不到指定的路
径。)
klass == class java.lang.System
.\bin\java\lang\StringBuilder.class
java.io.FileNotFoundException: .\bin\java\lang\StringBuilder.class (系统找不到指
定的路径。)
klass == class java.lang.StringBuilder
.\bin\java\io\PrintStream.class
java.io.FileNotFoundException: .\bin\java\io\PrintStream.class (系统找不到指定的
路径。)
klass == class java.io.PrintStream
嗨,bitan, 你终于找到我了!
C:\test>