Question

I'm using Javassist to get the Fields on a Class, using the following code:

for (CtField ctf : ctclass.getDeclaredFields()) {
    System.out.println(ctf.getName());
}

Thus, all the variables of the class to which I am accessing, are displayed on the screen and this works well.

What I want to know is it is possible to access the value of any of these variables?

Thanks for your help!

Was it helpful?

Solution 2

Finally it wasn't' necessary to use Javassist. With Java Reflect was enough, in this way:

String tempClassPath = tempDirPath + serviceName + sbbJarCmpt;

Where tempClassPath is the Path location of the service .jar file.

Now, with Java Reflect:

URL[] classes = {new File(tempClassPath).toURI().toURL()};
URLClassLoader child = new URLClassLoader (classes, this.getClass().getClassLoader());
Class fieldClass = Class.forName(className, true, child);

With this, I get an instance of the class and I can continue with the rest of the process.

OTHER TIPS

The only way to get the values of these variables is if you have an instance of the object for which you want to get the values for (since different instances may have different values).

Object instance = ...
...
for (CtField ctf : ctclass.getDeclaredFields()) {
    Field f = instance.getClass().getDeclaredField(ctf.getName());
    f.setAccessible(true);
    Object value = f.get(instance);
}

If you're trying to access static fields then you don't need the instance and you can just do f.get(null) in the code above.

Also, if you are using this for some sort of profiling along with java instrumentation or something like that and you do not have any instances of the objects you are inspecting, a viable strategy would be to add a static field that is a Collection of instances to each class (using javassist) and then transform all constructors (using insertAfter) to add this to that field. Then you can use the same reflection method in my example to get this new field from each class that you care about and thus you will have a reference to all instances.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top