1/** 2 * Copyright (C) 2009 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 17package com.google.inject.internal; 18 19 20import com.google.common.base.Preconditions; 21 22import java.lang.reflect.InvocationHandler; 23import java.lang.reflect.InvocationTargetException; 24import java.lang.reflect.Method; 25 26class DelegatingInvocationHandler<T> implements InvocationHandler { 27 28 private volatile boolean initialized; 29 30 private T delegate; 31 32 public Object invoke(Object proxy, Method method, Object[] args) 33 throws Throwable { 34 try { 35 // checking volatile field for synchronization 36 Preconditions.checkState(initialized, 37 "This is a proxy used to support" 38 + " circular references. The object we're" 39 + " proxying is not constructed yet. Please wait until after" 40 + " injection has completed to use this object."); 41 Preconditions.checkNotNull(delegate, 42 "This is a proxy used to support" 43 + " circular references. The object we're " 44 + " proxying is initialized to null." 45 + " No methods can be called."); 46 47 // TODO: method.setAccessible(true); ? 48 // this would fix visibility errors when we proxy a 49 // non-public interface. 50 return method.invoke(delegate, args); 51 } catch (IllegalAccessException e) { 52 throw new RuntimeException(e); 53 } catch (IllegalArgumentException e) { 54 throw new RuntimeException(e); 55 } catch (InvocationTargetException e) { 56 throw e.getTargetException(); 57 } 58 } 59 60 void setDelegate(T delegate) { 61 this.delegate = delegate; 62 initialized = true; 63 } 64} 65