This example Java source code file (MiniGuice.java) is included in the alvinalexander.com
"Java Source Code
Warehouse" project. The intent of this project is to help you "Learn
Java by Example" TM.
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.mini;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import javax.inject.Provider;
/**
* Proof of concept. A tiny injector suitable for tiny applications.
*
* @author jessewilson@google.com (Jesse Wilson)
* @since 3.0
*/
public final class MiniGuice {
private static final Object UNINITIALIZED = new Object();
private MiniGuice() {}
private final Map<Key, Provider>> bindings = new HashMap>();
private final Queue<RequiredKey> requiredKeys = new ArrayDeque();
private final Set<Key> singletons = new HashSet();
/**
* Creates an injector defined by {@code modules} and immediately uses it to
* create an instance of {@code type}. The modules can be of any type, and
* must contain {@code @Provides} methods.
*
* <p>The following injection features are supported:
* <ul>
* <li>Field injection. A class may have any number of field injections, and
* fields may be of any visibility. Static fields will be injected each
* time an instance is injected.
* <li>Constructor injection. A class may have a single {@code
* @Inject}-annotated constructor. Classes that have fields injected
* may omit the {@link @Inject} annotation if they have a public
* no-arguments constructor.
* <li>Injection of {@code @Provides} method parameters.
* <li>{@code @Provides} methods annotated {@code @Singleton}.
* <li>Constructor-injected classes annotated {@code @Singleton}.
* <li>Injection of {@link Provider}s.
* <li>Binding annotations on injected parameters and fields.
* <li>Guice annotations.
* <li>JSR 330 annotations.
* <li>Eager loading of singletons.
* </ul>
*
* <p>Note that method injection is not supported.
*/
public static <T> T inject(Class type, Object... modules) {
Key key = new Key(type, null);
MiniGuice miniGuice = new MiniGuice();
for (Object module : modules) {
miniGuice.install(module);
}
miniGuice.requireKey(key, "root injection");
miniGuice.addJitBindings();
miniGuice.addProviderBindings();
miniGuice.eagerlyLoadSingletons();
Provider<?> provider = miniGuice.bindings.get(key);
return type.cast(provider.get());
}
private void addProviderBindings() {
Map<Key, Provider>> providerBindings = new HashMap>();
for (final Map.Entry<Key, Provider>> binding : bindings.entrySet()) {
Key key = binding.getKey();
final Provider<?> value = binding.getValue();
Provider<Provider>> providerProvider = new Provider>() {
public Provider<?> get() {
return value;
}
};
providerBindings.put(new Key(new ProviderType(javax.inject.Provider.class, key.type),
key.annotation), providerProvider);
}
bindings.putAll(providerBindings);
}
private void requireKey(Key key, Object requiredBy) {
if (key.type instanceof ParameterizedType
&& (((ParameterizedType) key.type).getRawType() == Provider.class
|| ((ParameterizedType) key.type).getRawType() == javax.inject.Provider.class)) {
Type type = ((ParameterizedType) key.type).getActualTypeArguments()[0];
key = new Key(type, key.annotation);
}
requiredKeys.add(new RequiredKey(key, requiredBy));
}
private void eagerlyLoadSingletons() {
for (Key key : singletons) {
Provider<?> provider = bindings.get(key);
final Object onlyInstance = provider.get();
bindings.put(key, new Provider<Object>() {
public Object get() {
return onlyInstance;
}
});
}
}
public void install(Object module) {
boolean hasProvidesMethods = false;
for (Class<?> c = module.getClass(); c != Object.class; c = c.getSuperclass()) {
for (Method method : c.getDeclaredMethods()) {
if (method.isAnnotationPresent(com.google.inject.Provides.class)) {
Key key = key(method, method.getGenericReturnType(), method.getAnnotations());
addProviderMethodBinding(key, module, method);
hasProvidesMethods = true;
}
}
}
if (!hasProvidesMethods) {
throw new IllegalArgumentException("No @Provides methods on " + module);
}
}
private void addProviderMethodBinding(Key key, final Object instance, final Method method) {
final Key[] parameterKeys = parametersToKeys(
method, method.getGenericParameterTypes(), method.getParameterAnnotations());
method.setAccessible(true);
final Provider<Object> unscoped = new Provider
Other Java examples (source code examples)
Here is a short list of links related to this Java MiniGuice.java source code file: