Juice injector throwing null pointer exception

1,581 views
Skip to first unread message

ram siddarth

unread,
Mar 17, 2019, 2:50:35 PM3/17/19
to google-guice
0

Am trying to learn google juice. I have a InstallConfigurationModule class which has all the dependency needed to create an object of typeA and TypeB .And, got a class say class Car as shown Below and am trying to do constructor injection. When the run method is called am getting null pointer exception at system.out.println line. I know for sure that ModuleA, ModuleB has a reference on creating TypeA, TypeB since in my InstallConfigurationModulemodule, if I say Bind(TypeA.class)or Bind(TypeB.class), I get google juice error, 'A binding to typeA or typeB already configured'.

public class InstallConfigurationModule extends AbstractModule {

@Override
    protected void configure() {
        install(new ModuleA());
        install(new ModuleB());
    }
}
public class Car

{
  private Type A;
  private Type B;

@inject
  void SetCar(Type A, Type B)//not the constructor
 {
   this.A=A;
   this.B=B;
}

private void run()
{
  System.out.println(A.toString()) //throw null pointer exception
}

what Worked:

private void run()
    { 
     Injector injector = Guice.createInjector(new 
                         InstallConfigurationModule());

    TypeA typeA =injector.getInstance(TypeA.class);
      System.out.println(A.toString()) //works fine

    }

Why do I get NPE when I try to do without creatingInjector. Any help appreciated.

PS: very new to juice.

scl

unread,
Mar 18, 2019, 4:22:22 AM3/18/19
to google-guice
How do you run the example where the NPE occurs?
Guice can only inject instances which are created by Guice or are passed to the method injector.injectMembers().

I highly recommend to use constructor injection over field or method injection.
Especially because it makes testing without Guice easier.

ram siddarth

unread,
Mar 19, 2019, 8:17:02 PM3/19/19
to google-guice
Run() is called from an Injected instance, looks like the object isn't null but the ToString() seems to throw null instead of NPE. 
Looking at the stack trace.
Caused by: java.lang.NoSuchMethodException:com.example.car.ToString().

scl

unread,
Mar 20, 2019, 2:30:39 AM3/20/19
to google-guice
Without more code it is almost impossible to help...

What I notice is that you call the method ToString() with a capital T.
In java the method is called toString() with a non capital T.

But this would have been caught by the compiler. So I really start to wonder how this could be...
Reply all
Reply to author
Forward
0 new messages