日期:2014-05-20 浏览次数:20850 次
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Test {
public class MyLoader extends ClassLoader {
private final String path = getClass().getResource("/").getPath();
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] b = getData(name);
return defineClass(name, b, 0, b.length);
}
private byte[] getData(String url) {
byte[] b = null;
try (FileInputStream reader = new FileInputStream(new StringBuffer(
path).append(url.replace('.', File.separatorChar))
.append(".class").toString())) {
b = new byte[reader.available()];
reader.read(b, 0, b.length);
} catch (IOException e) {
e.printStackTrace();
}
return b;
}
}
public static void main(String[] args) throws Exception {
new Test().foo();
}
private void foo() throws Exception {
Class<?> cls = Foo.class;
/* 使用MyLoader加载非public类 */
// cls = new MyLoader().findClass(Foo.class.getName());
Object obj = cls.newInstance();// java.lang.IllegalAccessException异常
cls.getDeclaredMethod("bar").invoke(obj);
}
}
/*public*/ class Foo {
public void bar() {
System.out.println("asdfghjkl");
}
}
public T newInstance()
throws InstantiationException, IllegalAccessException
{
if (System.getSecurityManager() != null) {
checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
}
return newInstance0();
}