bineanzhou / google-guice

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

Binding to an abstract class causes NullPointerException at getInstance() time #184

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Consider this code:

package com.google.guicetest;

import com.google.inject.*;

public class GuiceTest {

  public static abstract class AbstractThing {
    public void doIt() {
      doItImpl();
    }
    protected abstract void doItImpl();
  }

  public static abstract class AccidentallyAbstract extends AbstractThing {
    @Override protected void doItImpl() {
      System.out.println("AccidentallyAbstract");
    }
  }

  public static void main(String args[]) {
    Injector injector = Guice.createInjector(new AbstractModule() {
      @Override public void configure() {
        bind(AbstractThing.class).to(AccidentallyAbstract.class);
      }
    });
    AbstractThing at = injector.getInstance(AbstractThing.class);
    at.doIt();
  }
}

Running this produces:

Exception in thread "main" java.lang.NullPointerException
        at
com.google.inject.BindingBuilderImpl$FactoryProxy.get(BindingBuilderImpl.java:29
9)
        at com.google.inject.InjectorImpl$9$1.call(InjectorImpl.java:708)
        at com.google.inject.InjectorImpl.callInContext(InjectorImpl.java:747)
        at com.google.inject.InjectorImpl$9.get(InjectorImpl.java:702)
        at com.google.inject.InjectorImpl.getInstance(InjectorImpl.java:728)
        at com.google.guicetest.GuiceTest.main(GuiceTest.java:26)

Now, I realize that the binding shouldn't have worked - after all,
AccidentallyAbstract is an abstract class, and I didn't supply any binding
for AccidentallyAbstract.  However, I should get an error saying "no
binding for AccidentallyAbstract" or "AccidentallyAbstract is an abstract
class", or something similar.  I shouldn't get a NullPointerException.

Although obvious in this case because I named the classes to highlight the
accidental "abstract" declaration, the error can get very hard to debug and
buried in other layers of Guice error messages if there's some other class
which requires an AbstractThing as an injected constructor parameter.

I would prefer to get an error message when creating the injector itself,
rather than have this ticking bomb waiting to explode when I ask for an
instance of something that eventually requires an instance of AbstractThing.

Original issue reported on code.google.com by d...@google.com on 6 Mar 2008 at 12:51

GoogleCodeExporter commented 9 years ago

Original comment by limpbizkit on 14 May 2008 at 3:30