我尝试扩展 ClassLoader。我的 ClassLoader.loadClass 是:
protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {// i put "throw"s here to clean code below
Class<?> result = null;
byte[] bytes = null;
try {
bytes = getClassFromFS(pathToClass); //get .class file from file system in bytes[]
} catch (FileNotFoundException ex) {
Logger.getLogger(MyLoader.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MyLoader.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("MyLoader:мой loadClass загружает класс");
return defineClass(name, bytes, 0, bytes.length); // the proplem is here !!!
return super.loadClass(name, resolve);
}
“主”线程中的行
/*first argument - path to file. File exist, I checked it*/
myClassLoader = new MyLoader("D:\\\\customclassloader\\ClassX.class", ClassLoader.getSystemClassLoader());
classX = (SimpleInterface) myClassLoader.loadClass("customclassloader.ClassX",true).newInstance();
</pre>
then I have exception
<pre>Exception in thread "main" java.lang.SecurityException: Prohibited package name: java.lang
at java.lang.ClassLoader.preDefineClass(ClassLoader.java:650)
at java.lang.ClassLoader.defineClass(ClassLoader.java:786)
at java.lang.ClassLoader.defineClass(ClassLoader.java:635)
at customclassloader.MyLoader.loadClass(MyLoader.java:61)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:792)
at java.lang.ClassLoader.defineClass(ClassLoader.java:635)// the proplem is here !!!
at customclassloader.MyLoader.loadClass(MyLoader.java:61)
at customclassloader.CustomClassLoader.main(CustomClassLoader.java:32)
X 类:
package customclassloader;
/**
*
* @author roman
*/
public class ClassX {
static {
System.out.println("класс ClassX инициируеться");
}
public ClassX() {
System.out.println("класс ClassX конструируеться");
}
public void f(){
System.out.println("класс ClassX выполняет f();");
}
}
我不明白。我将类命名为“customclassloader.ClassX”。为什么它显示名称“java.lang”?ClassX.class 在同一个项目和同一个包中编译。