dimanche 4 janvier 2015

Why does Class.newInstance always throw an exception?

I want to define a custom class loader to load my own class at run-time.


However, Class.newInstance always fails even if I defined a zero-argument constructor.


The exception message is:


java.lang.IllegalAccessException: Class Hello can not access a member of class Test with modifiers "public"


Why?



import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

class CustomClassLoader extends ClassLoader {

private Map<String, Class<?>> classes = new HashMap<String, Class<?>>();

public String toString() {
return CustomClassLoader.class.getName();
}

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {

if (classes.containsKey(name)) {
return classes.get(name);
}

byte[] classData;

try {
classData = loadClassData(name);
} catch (IOException e) {
throw new ClassNotFoundException("Class [" + name
+ "] could not be found", e);
}

Class<?> c = defineClass(name, classData, 0, classData.length);
resolveClass(c);
classes.put(name, c);

return c;
}

private byte[] loadClassData(String name) throws IOException {
BufferedInputStream in = new BufferedInputStream(
ClassLoader.getSystemResourceAsStream(name.replace(".", "/")
+ ".class"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
int i;

while ((i = in.read()) != -1) {
out.write(i);
}

in.close();
byte[] classData = out.toByteArray();
out.close();

return classData;
}
}

class Test
{
public Test()
{}

public void Hello()
{}
}

public class Hello {

public static void main(String[] args)
{
try {
CustomClassLoader loader = new CustomClassLoader();
Class<?> c = loader.findClass("Test"); // OK!
Object o = c.newInstance(); // ALWAYS FAIL!
}
catch (Exception e)
{
String s = e.getMessage();
// s is "java.lang.IllegalAccessException: Class Hello can not access"
// " a member of class Test with modifiers "public""
}
}
}





Aucun commentaire:

Enregistrer un commentaire