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.lang.reflect.Modifier; 019 020import org.mockito.cglib.proxy.MethodInterceptor; 021import org.mockito.exceptions.base.MockitoException; 022import org.mockito.internal.creation.jmock.ClassImposterizer; 023 024/** 025 * This {@link ProxyFactory} uses Mockito's jmock package to create proxies that subclass from the target's class. 026 * 027 * @author rwoo 028 */ 029public class SubclassProxyFactory implements ProxyFactory { 030 031 /** 032 * That proxy factory is used if this factory cannot be used. 033 */ 034 private ProxyFactory fallbackProxyFactory = new InterfaceOnlyProxyFactory(); 035 036 /* 037 * (non-Javadoc) 038 * 039 * @see com.googlecode.catchthrowable.internal.ProxyFactory#createProxy(java. lang.Object, java.lang.Class, boolean) 040 */ 041 @Override 042 @SuppressWarnings("unchecked") 043 public <T> T createProxy(Class<?> targetClass, MethodInterceptor interceptor) { 044 045 // can we subclass the class of the target? 046 if (!isTypeMockable(targetClass)) { 047 048 // delegate 049 return fallbackProxyFactory.<T>createProxy(targetClass, interceptor); 050 } 051 052 // create proxy 053 T proxy; 054 try { 055 056 proxy = (T) ClassImposterizer.INSTANCE.imposterise(interceptor, targetClass); 057 058 } catch (MockitoException e) { 059 060 // delegate 061 return fallbackProxyFactory.<T>createProxy(targetClass, interceptor); 062 } 063 064 return proxy; 065 } 066 067 public boolean isTypeMockable(Class<?> type) { 068 return !type.isPrimitive() && !Modifier.isFinal(type.getModifiers()); 069 } 070 071}