001/** 002 * Copyright (C) 2011 rwoo@gmx.de 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.googlecode.catchexception.throwable.internal; 017 018import java.util.HashSet; 019import java.util.Set; 020 021import org.mockito.cglib.proxy.Enhancer; 022import org.mockito.cglib.proxy.MethodInterceptor; 023 024/** 025 * This {@link ProxyFactory} create proxies that implements all interfaces of 026 * the underlying object including the marker interface 027 * {@link InterfaceOnlyProxy}. But in contrast to the proxies created by 028 * {@link SubclassProxyFactory} such a proxy does not subclass the class of the 029 * underlying object. 030 * 031 * @author rwoo 032 */ 033public class InterfaceOnlyProxyFactory implements ProxyFactory { 034 035 /* 036 * (non-Javadoc) 037 * 038 * @see 039 * com.googlecode.catchthrowable.internal.ProxyFactory#createProxy(java. 040 * lang.Class, org.mockito.cglib.proxy.MethodInterceptor) 041 */ 042 @SuppressWarnings("unchecked") 043 public <T> T createProxy(Class<?> targetClass, MethodInterceptor interceptor) { 044 045 // get all the interfaces (is there an easier way?) 046 Set<Class<?>> interfaces = new HashSet<Class<?>>(); 047 Class<?> clazz = targetClass; 048 while (true) { 049 for (Class<?> interfaze : clazz.getInterfaces()) { 050 interfaces.add(interfaze); 051 } 052 if (clazz.getSuperclass() == null) { 053 break; 054 } 055 clazz = clazz.getSuperclass(); 056 } 057 interfaces.add(InterfaceOnlyProxy.class); 058 059 return (T) Enhancer.create(Object.class, 060 interfaces.toArray(new Class<?>[interfaces.size()]), 061 interceptor); 062 } 063}