KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > inject > DefaultConstructionProxyFactory


1 /**
2  * Copyright (C) 2006 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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  */

16
17 package com.google.inject;
18
19 import com.google.inject.util.GuiceFastClass;
20 import com.google.inject.util.Objects;
21 import java.lang.reflect.Constructor JavaDoc;
22 import java.lang.reflect.InvocationTargetException JavaDoc;
23 import java.lang.reflect.Modifier JavaDoc;
24 import net.sf.cglib.reflect.FastClass;
25 import net.sf.cglib.reflect.FastConstructor;
26
27 /**
28  * Default {@link ConstructionProxyFactory} implementation. Simply invokes the
29  * constructor. Can be reused by other {@code ConstructionProxyFactory}
30  * implementations.
31  *
32  * @author crazybob@google.com (Bob Lee)
33  */

34 class DefaultConstructionProxyFactory implements ConstructionProxyFactory {
35
36   public <T> ConstructionProxy<T> get(final Constructor JavaDoc<T> constructor) {
37     // We can't use FastConstructor if the constructor is private or protected.
38
if (Modifier.isPrivate(constructor.getModifiers())
39         || Modifier.isProtected(constructor.getModifiers())) {
40       constructor.setAccessible(true);
41       return new ConstructionProxy<T>() {
42         public T newInstance(Object JavaDoc... arguments) throws
43             InvocationTargetException JavaDoc {
44           Objects.assertNoNulls(arguments);
45           try {
46             return constructor.newInstance(arguments);
47           }
48           catch (InstantiationException JavaDoc e) {
49             throw new RuntimeException JavaDoc(e);
50           }
51           catch (IllegalAccessException JavaDoc e) {
52             throw new AssertionError JavaDoc(e);
53           }
54         }
55       };
56     }
57
58     Class JavaDoc<T> classToConstruct = constructor.getDeclaringClass();
59     FastClass fastClass = GuiceFastClass.create(classToConstruct);
60     final FastConstructor fastConstructor
61         = fastClass.getConstructor(constructor);
62     return new ConstructionProxy<T>() {
63       @SuppressWarnings JavaDoc("unchecked")
64       public T newInstance(Object JavaDoc... arguments)
65           throws InvocationTargetException JavaDoc {
66         Objects.assertNoNulls(arguments);
67         return (T) fastConstructor.newInstance(arguments);
68       }
69     };
70   }
71 }
72
Popular Tags