Results 1 to 4 of 4
  1. #1
    veronique is offline Member
    Join Date
    Apr 2011
    Posts
    22
    Rep Power
    0

    Default Guice Injection + Anonymous inner classes ??

    Hi Java experts,

    I have been using Guice for a while but just now run into a need to use anonymous inner classes. In the example below Car and its dependencies do not get injected resulted in NPE on consecutive calls. How can this be changed to work properly? Do I need to add extra binding?

    public class Truck {
    @Inject
    public Truck(Engine engine) {
    this.engine = engine;
    }

    public Car getCar() {
    return new Car() {
    @Override
    public void drive() {
    ....
    }
    };
    }
    }

    thanks!

  2. #2
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,185
    Rep Power
    20

    Default Re: Guice Injection + Anonymous inner classes ??

    The outer class will need to know about the things needed for constructing the anonymous class.
    Which makes sense as the outer class is acting as a factory.

    I hope that the example you give is just that, an example. Because a Truck making a Car makes no sense (unless it's some sort of mobile factory).
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    veronique is offline Member
    Join Date
    Apr 2011
    Posts
    22
    Rep Power
    0

    Default Re: Guice Injection + Anonymous inner classes ??

    Yes that just an example of Car being parent class and Truck a sub class without using inheritance.

    So are there any examples of using Guice + anonymous class?

  4. #4
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,185
    Rep Power
    20

    Default Re: Guice Injection + Anonymous inner classes ??

    You don't use Guice to inject into an anonymous class.
    Which is what I implied in the first two sentences of my post.

    Well, you could use it, but that would involve getting an injector in the code, and that's not good practice.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Replies: 7
    Last Post: 02-26-2009, 07:46 AM
  2. Anonymous classes ...
    By Nicholas Jordan in forum Advanced Java
    Replies: 6
    Last Post: 11-27-2008, 07:02 PM
  3. Replies: 0
    Last Post: 03-29-2008, 01:38 PM
  4. Replies: 0
    Last Post: 03-29-2008, 01:38 PM
  5. Replies: 0
    Last Post: 09-26-2007, 09:29 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •