Hello, I have a problem: I need to change the value of a Field to a proxy.
My proxy works perfectly, but I can not modify a Field. Whenever I try it returns an IllegalArgumentException saying that I can not set the field of such type to Proxy.
My goal is to set this field without needing any import, ie without extending or implementing anything.
Example of what's happening:
public class ClasseAlvo {
Classe2 con;
}
I need to set the variable "con" through a Proxy made of "Class2", the proxy is successfully done and my problem is to set the variable with my proxy.
public class ClasseProxy implements InvocationHandler {
Object pc;
public ClasseProxy(Object original) {
this.pc = original;
}
public Object invocaFuncao(Method m, Object[] args) {
try {
return pc.getClass().getMethod(m.getName(), m.getParameterTypes()).invoke(pc, args);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
@Override
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
if(m.getName().equalsIgnoreCase("teste")) {
System.out.println("Metodo teste foi executado.");
} else {
return invocaFuncao(m, args);
}
return null;
}
}
And my interface:
public interface IClasse {
public void teste(String nome);
}
My proxy and where the error is:
IClasse pc = (IClasse)Proxy.newProxyInstance(getClass().getClassLoader(),
new Class[] {IClasse.class},
new ClasseProxy(obj));
Field f = alvo.getClass().getDeclaredField("con");
f.setAccessible(true);
f.set(alvo, pc); // <--- O PROBLEMA
Any help is welcome.