How do i return a proxied object from provider ?

128 views
Skip to first unread message

lei wang

unread,
Nov 3, 2016, 10:48:42 PM11/3/16
to google-guice
I want to add an interceptor to a 3rd party class. Since it does not have a no-arg constructor, I'd have to use a provider to create an instance. But it seems that provider returns a raw object (no proxy), and I can't intercept it. Do i miss something? How can I add an interceptor to a class without no-arg constructor ? Here is a snippet..

class Foo {
    public Foo(int value) {...}

    public void exec() {...}
}

class Bar {
     public void bar() {...}
}

class FooBarModule extends AbstractModule {
    protected void configure() {
        bind(Foo.class).toProvider(FooProvider.class);
        bind(Bar.class);

         bindInterceptor(Matchers.subclassesOf(Foo.class).or(Matchers.subclassesOf(Bar.class)), Matchers.any(), new FooBarInterceptor());
    }
}


class FooMain {
    public static void main(String[] args) {
       Injector injector = Guice.createInjector(new FooModule());
       Foo fooObj = injector.getInstance(Foo.class);

       fooObj.exec();           // FooBarInterceptor is NOT triggered, because fooObj is a raw object.

       Bar barObj = injector.getInstance(Bar.class);
       barObj.bar();             // FooBarInterceptor is triggeredas expected. barObj is a Guice proxied object
}


lei wang

unread,
Nov 3, 2016, 11:01:36 PM11/3/16
to google-guice
class FooProvider implements Provider<Foo> {
    public Foo get() {
        return new Foo(10);

Thomas Broyer

unread,
Nov 4, 2016, 6:23:32 AM11/4/16
to google-guice
Could you maybe create a Foo subclass?

class SubFoo extends Foo {
  public SubFoo() {
    super(10);
  }
}
bind(Foo.class).to(SubFoo.class);
bindInterceptor(…)…

lei wang

unread,
Nov 4, 2016, 9:21:09 AM11/4/16
to google-guice
If I have to, that would be one option.

But I am wondering why Guice does not add a proxy to the objects which are returned from a Provider. After all, Guice calls Provider.get(), and it does have a chance to add a proxy. Because I get the object through injector.getInstance(), it is confusing that some have proxies, and some don't depending on they are created behind scene.

Thomas Broyer

unread,
Nov 4, 2016, 1:15:29 PM11/4/16
to google-guice
AFAIK, Guice doesn't create a proxy, it synthesizes a subclass that overrides matched methods and then instantiate them instead of the original class.

lei wang

unread,
Nov 4, 2016, 2:35:38 PM11/4/16
to google-guice
Sorry I might use the term "proxy" loosely. What I meant is that - if an object is instantiated by Guice (not through a Provider), the object is enhanced by Guice, and the string rep of the object has $$EnhancerByGuice$$.... But if an object is created by a Provider, it is not enhanced by Guice.

Is there an API to make a provider-instantiated object to be "enhanced by Guice" ?

Thank you very much for your responses.
Reply all
Reply to author
Forward
0 new messages