01: /**
02: * Copyright (C) 2006 Google Inc.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */package com.google.inject;
16:
17: import com.google.inject.util.GuiceFastClass;
18: import com.google.inject.util.Objects;
19: import java.lang.reflect.Constructor;
20: import java.lang.reflect.InvocationTargetException;
21: import java.lang.reflect.Modifier;
22: import net.sf.cglib.reflect.FastClass;
23: import net.sf.cglib.reflect.FastConstructor;
24:
25: /**
26: * Default {@link ConstructionProxyFactory} implementation. Simply invokes the
27: * constructor. Can be reused by other {@code ConstructionProxyFactory}
28: * implementations.
29: *
30: * @author crazybob@google.com (Bob Lee)
31: */
32: class DefaultConstructionProxyFactory implements
33: ConstructionProxyFactory {
34:
35: public <T> ConstructionProxy<T> get(final Constructor<T> constructor) {
36: // We can't use FastConstructor if the constructor is private or protected.
37: if (Modifier.isPrivate(constructor.getModifiers())
38: || Modifier.isProtected(constructor.getModifiers())) {
39: constructor.setAccessible(true);
40: return new ConstructionProxy<T>() {
41: public T newInstance(Object... arguments)
42: throws InvocationTargetException {
43: Objects.assertNoNulls(arguments);
44: try {
45: return constructor.newInstance(arguments);
46: } catch (InstantiationException e) {
47: throw new RuntimeException(e);
48: } catch (IllegalAccessException e) {
49: throw new AssertionError(e);
50: }
51: }
52: };
53: }
54:
55: Class<T> classToConstruct = constructor.getDeclaringClass();
56: FastClass fastClass = GuiceFastClass.create(classToConstruct);
57: final FastConstructor fastConstructor = fastClass
58: .getConstructor(constructor);
59: return new ConstructionProxy<T>() {
60: @SuppressWarnings("unchecked")
61: public T newInstance(Object... arguments)
62: throws InvocationTargetException {
63: Objects.assertNoNulls(arguments);
64: return (T) fastConstructor.newInstance(arguments);
65: }
66: };
67: }
68: }
|