Java reflection question

Natan Griefwell picture Natan Griefwell · Jul 12, 2011 · Viewed 10.8k times · Source

I am working on a project that uses reflection to get the fields of a running java application.

I managed to get the fields, but I can not read or write to them. This is an example I found on the web:

Class aClass = MyObject.class
Field field = aClass.getField("someField");
MyObject objectInstance = new MyObject();
Object value = field.get(objectInstance);
field.set(objetInstance, value);

The problem is that I use classes from a running jar file, and the classes I try to manipulate are obtained from the classLoader. So instead of 'MyObject.class' I just have the '.class'. To get the 'MyObject' I tried to use a ClassLoader but that did not work.

If I just use '.class':

Object value = field.get(theLoadedClass);

I will get this error:

java.lang.IllegalArgumentException: Can not set int field myClass.field to java.lang.Class

Thanks.

Answer

JB- picture JB- · Jul 12, 2011

This should help:

Class aClass = myClassLoader.loadClass("MyObject"); // use your class loader and fully qualified class name
Field field = aClass.getField("someField");
// you can not use "MyObject objectInstance = new MyObject()" since its class would be loaded by a different classloader to the one used to obtain "aClass"
// instead, use "newInstance()" method of the class
Object objectInstance = aClass.newInstance();
Object value = field.get(objectInstance);
field.set(objetInstance, value);