How google guice works internally

dependency-injection, guice, java, reflection

Solution

Your understanding is a little off. Think of it this way: when you do `Guice.createInjector(...)`, that's when Guice does all the reflection to figure out what depends on what and what needs to get injected where. When you do `injector.getInstance(...)`, Guice doesn't need to do any reflection. It creates the `RealBillingService` right then, injecting all its (transitive) dependencies, and returns that (not a proxy).

If you use Guice's AOP functionality then those objects will be proxies, but otherwise Guice doesn't return proxies. It simply invokes the `@Inject` constructor, sets the `@Inject`-annotated fields, calls the `@Inject`-annotated methods, and returns that object.

EDIT: See also MiniGuice, a single-class implementation of a Guice-like injector.

Problem

I was going through the google `guice` and then i thought about how it might be working. So This is my theory on how `property injector` might be working. `Guice` first wants us to create a `injector` and pass all the `binding` information to it. ``` Injector injector = Guice.createInjector(new BillingModule()); ``` *code snippets from google guice page OK at this point i can think that there is a class with all the information of `binding`. and when we do ``` injector.getInstance(RealBillingService.class); ``` Here we do the trick. `injector` will return a `proxy instance` for the real `RealBillingService` object and when we call a method of `RealBillingService` object, `proxy instance` invocation handler uses `reflection` to figure out the properties to inject and fullfill it based on the information passed during the creation of injector. QUESTION This is the way i suppose, the `guice` works. If i am wrong, what would be the actual way by which `'Guice'` achieve it ? If this is the way `guice` work then `Guice` always returns the `proxy object` and the user code always makes call on the `proxy objects`. is this true ? Pictorial representation on my explaination

Original source