2
Hello, I’m having a problem: I need to change the value of a Field to a proxy.
My proxy works perfectly, but I can’t modify a Field. Whenever I try returns me an Illegalargumentexception saying 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 is happening:
public class ClasseAlvo {
Classe2 con;
}
I need to set the variable "con" through a proxy made of "Classe2", the proxy is done successfully 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 is the error:
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.
Could show the code snippet that is in trouble?
– Math
Edited with code (cleaner version) to show my problem. I also wanted to know if it’s possible to do what I’m trying to do and if there’s another way to do it...
– Guilherme Chaguri