在java.lang.reflect.Proxy中替换InvocationHandler

时间:2013-06-18 15:13:17

标签: java proxy

我需要在Proxy对象中替换InvocationHandler。但它只有吸气剂而且没有制定者。为什么会这样,有没有解决办法?

由于

1 个答案:

答案 0 :(得分:0)

我认为你需要保持相同的调用处理程序,但要改变它的行为。如果在调用处理程序中使用State模式,这将更接近您正在寻找的内容:

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;
    }
}