frjaeger220 / google-guice

Automatically exported from code.google.com/p/google-guice
Apache License 2.0
0 stars 0 forks source link

bind(Interface).toConstructor(ConstructorInImpl) fails #434

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Ran across this while trying to hack up a solution for the new
AssistedInject to work with multiple matching constructors (similar to how
the old version of it worked).  The fix is pretty simple, so I'll just
paste the change here since I've got other local changes & building a patch
would be a pain.

In ConstructorBindingImpl.create, instead of having:

  Class<? super T> rawType = key.getTypeLiteral().getRawType();

it should have:

    Class<? super T> rawType;
    if(constructorInjector == null) {
      rawType = key.getTypeLiteral().getRawType();
    } else {
      // safe cast -- impossible for the constructInjector not to be the
right type
      rawType = (Class<? super
T>)constructorInjector.getDeclaringType().getRawType();
    }

The reason is because later on it uses the rawType to do various sanity
checks (such as checking for abstractness, if it's an inner class, etc..),
and when you explicitly specify a constructor, you want those checks to be
on the constructor's type, not the type of the binding it was linked to.

Added an additional test into BindingTest:

  public void testInterfaceToImplementationConstructor() throws
NoSuchMethodException {
    final Constructor<CFoo> constructor = CFoo.class.getDeclaredConstructor();

    Injector injector = Guice.createInjector(new AbstractModule() {
      protected void configure() {
        bind(IFoo.class).toConstructor(constructor);
      }
    });

    injector.getInstance(IFoo.class); 
  }

  public static interface IFoo {}
  public static class CFoo implements IFoo {}

Before applying the patch, the test fails.  Afterwards it passes.

Original issue reported on code.google.com by sberlin on 5 Oct 2009 at 3:06

GoogleCodeExporter commented 9 years ago
Fixed with r1119.

Original comment by limpbizkit on 12 Oct 2009 at 11:17

GoogleCodeExporter commented 9 years ago
Just want to ping this issue.  Although the signature currently allows
bind(T).toConstructor(S extends T), the implementation in ConstructorBindingImpl
fails when T is an interface & S is a valid class that implements T.  (The 
patch,
written in the issue description, fixes the issue & provides a test-case.)

Original comment by sberlin on 12 Oct 2009 at 11:18

GoogleCodeExporter commented 9 years ago
Ha, talk about timing. :-)

Original comment by sberlin on 12 Oct 2009 at 11:18

GoogleCodeExporter commented 9 years ago
Rock on JW

Original comment by dha...@gmail.com on 13 Oct 2009 at 12:00