IllegalAccessError caused by custom class loader
I want to load the javax.swing.UIManager class with my custom class loader, and set the look and feel via reflection. My class loader source is here:
package com.test;
import java.io.InputStream;
import java.lang.reflect.Method;
publicclass TestClassLoaderextends ClassLoader{
public Class<?> loadClass(String name)throws ClassNotFoundException{
if (name.equals("javax.swing.UIManager")){
try{
String classFileName = name.replaceAll("\\.","/") +".class";
InputStream is = getSystemResourceAsStream(classFileName);
if (is ==null){
System.out.println("Can not get UIManager.class as stream.");
}
byte[] buf =newbyte[is.available()];
int byteNum = 0;
while (byteNum < buf.length){
byteNum += is.read(buf, byteNum, buf.length);
}
Class newClass = this.defineClass(name, buf, 0, buf.length);
return newClass;
}catch (Error e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
return getParent().loadClass(name);
}
publicstaticvoid main(String[] args){
TestClassLoader cl =new TestClassLoader();
Thread.currentThread().setContextClassLoader(cl);
try{
Class uimgrClass = cl.loadClass("javax.swing.UIManager");
Method setLnfMethod = uimgrClass.getMethod("setLookAndFeel",new Class[]{cl.loadClass("javax.swing.LookAndFeel")});
Class lnfClass = cl.loadClass("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
Object lnf = lnfClass.newInstance();
setLnfMethod.invoke(null,new Object[]{lnf});
}catch (Exception e){
e.printStackTrace();
}
}
}
When invoking the main() method, I got the following error message:
====================================================================
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at com.test.TestClassLoader.main(TestClassLoader.java:38)
Caused by: java.lang.IllegalAccessError: tried to access method javax.swing.SwingUtilities.appContextGet(Ljava/lang/Object;)Ljava/lang/Object; from class javax.swing.UIManager
at javax.swing.UIManager.getLAFState(UIManager.java:178)
at javax.swing.UIManager.setLookAndFeel(UIManager.java:431)
... 5 more
====================================================================
I don't know why there is an IllegalAccessError? Is there something I need to know when trying to implement such a custom class loader?

