Overriding a method in an instantiated Java object

前端 未结 9 1418
陌清茗
陌清茗 2021-02-05 01:55

I would like to override a method in an object that\'s handed to me by a factory that I have little control over.

My specific problem is that I want to override the

9条回答
  •  别跟我提以往
    2021-02-05 02:02

    Another proxying-related solution: you could use Aspects to override a method on a given object without subclassing it yourself. This is especially appropriate and common for logging. This example uses spring-aop.

    class Example {
    
        final Foo foo;
    
        Example(Foo original) {
            AspectJProxyFactory factory = new AspectJProxyFactory();
            factory.setTarget(original);
            factory.addAspect(FooAspect.class);
            foo = (Foo) factory.getProxy();
        }
    
        @Aspect
        static class FooAspect {
    
            @Before("execution(Foo.doBar())")
            Object beforeDoBar() {
                // My own activity
            }
        }
    

提交回复
热议问题