Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception trying to change a CGLib proxy field value

Tags:

java

proxy

cglib

I created a CGLib dynamic proxy of a class, but when I try to access any field declared in the original class, I obtain java.lang.NoSuchFieldException. I need to obtain the field in order to change its value.

By the way, this is the class the proxy is based on:

public class Person {

    private String name;
    ....
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    ...
}

And this is the code snippet (inside the "intercept" method of the "MethodInterceptor") that is raising the mentioned exception (more specifically the first line):

public Object intercept(Object instance, Method jdkMethod, Object[] args, MethodProxy method) throws Throwable {
...
Field field = instance.getClass().getField("name");
field.setAccessible(true);
field.set(instance, "foo");
....

Do you know any other way to access the needed field or change its value?

Thanks.

like image 778
Bruno Cartaxo Avatar asked Oct 17 '25 10:10

Bruno Cartaxo


2 Answers

Apparently, a CGLib proxy is a subclass of the original class. So, the following code worked well:

Field field = instance.getClass().getSuperclass().getDeclaredField("name");
like image 83
Bruno Cartaxo Avatar answered Oct 18 '25 23:10

Bruno Cartaxo


Try:

Field field = instance.getClass().getDeclaredField("name");

As mentioned in this SO answer, getField only works for public fields, but applies to the entire class hierarchy. You can think of it as inspecting the public interface of the class. getDeclaredField works for private fields, and will not inspect the class hierarchy; you can think of it as resolving the implementation of the class.

like image 40
Jeff Bowman Avatar answered Oct 19 '25 00:10

Jeff Bowman