dimanche 4 janvier 2015

How to use Reflection to access non-public fields of classes that are loaded with a different ClassLoader?

I am using a child URLClassLoader to load a jar at runtime, then I use the Google Reflections library to inspect the new classes I loaded. However, it seems that with the following code, I can only inspect public fields; I would also like to inspect non-public fields. (I have no problem with methods though!)



URL[] urls = new URL[]{jarPath.toUri().toURL()};
Reflections r = new Reflections(new ConfigurationBuilder().setUrls(urls).setScanners(
new SubTypesScanner(false)
));

URLClassLoader cl = URLClassLoader.newInstance(urls, ClassLoader.getSystemClassLoader());
for (String cls : r.getAllTypes()) {
System.out.println(cls);
Class<?> c = cl.loadClass(cls);
Field[] allFields = c.getDeclaredFields();
for (Field f : allFields) {
System.out.println('\t' + (f.getModifiers() & Modifier.PUBLIC) + " " + f.getName());
}

Method[] allMethods = c.getDeclaredMethods();
for (Method m : allMethods) {
System.out.println("\t\t" + (m.getModifiers() & Modifier.PUBLIC) + " " + m.getName());
}
}


What I am doing wrong?






Aucun commentaire:

Enregistrer un commentaire