简体   繁体   中英

Replace InvocationHandler in java.lang.reflect.Proxy

I need to replace InvocationHandler in a Proxy object. But there is only getter for it and no setter. Why is this so and is there any workaround?

Thanks

I think you'll need to keep the same invocation handler but have it change its behaviour. This will be closer to what you're looking for if you use the State pattern in the invocation handler:

public class Handler implements InvocationHandler
{
    HandlerState state = new NormalState();

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        // Make all method calls to the state object, not this object.
        this.state.doStuff();

        return this.state.doOtherStuff();
    }

    public void switchToErrorState(){
        this.state = new ErrorState();
    }
}

public interface HandlerState
{
    public void doStuff();
    public String doOtherStuff();
}

public class ErrorState implements HandlerState
{
    @Override
    public void doStuff() {
        // Do stuff we do in error mode
    }

    @Override
    public String doOtherStuff() {
        // Do other error mode stuff.
        return null;
    }
}

public class NormalState implements HandlerState
{
    @Override
    public void doStuff() {
        // Do normal stuff
    }

    @Override
    public String doOtherStuff() {
        // Do normal other stuff
        return null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM