In Java, is it possible to override methods in a class that you create using reflection
? For example, say I have the following class:
public class MyObject
{
public String foo, bar;
public MyObject(String foo)
{
this.foo = foo;
this.bar = foo + "bar";
}
public void setBar(String bar)
{
this.bar = bar;
}
}
And in one class I want to create it directly and override its setBar
method as follows:
MyObject obj = new MyObject("something")
{
@Override
public void setBar(String bar)
{
this.bar = this.foo;
}
};
Is there a way to override a method in this same manner using reflection? Maybe something like this? :
Class<?> _class = Class.forName("com.example.MyObject");
Constructor<?> _constructor = _class.getConstructor(new Class<?>[]{String.class});
Method m = _class.getMethod("setBar", new Class<?>[]{String.class});
Object obj = _constructor.newInstance("Foo String")
{
m = new Method(new Class<?>[]{String.class})
{
System.out.println("Foobar");
}
};
If not, are there other ways of doing this, or an external library that could help? I am looking for way to add listeners to a setter method in order to change binded values.