001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.pool2.proxy;
018
019import java.lang.reflect.Proxy;
020
021import org.apache.commons.pool2.UsageTracking;
022
023/**
024 * Provides proxy objects using Java reflection.
025 *
026 * @param <T> type of the pooled object to be proxied
027 *
028 * @since 2.0
029 */
030public class JdkProxySource<T> implements ProxySource<T> {
031
032    private final ClassLoader classLoader;
033    private final Class<?>[] interfaces;
034
035
036    /**
037     * Create a new proxy source for the given interfaces.
038     *
039     * @param classLoader The class loader with which to create the proxy
040     * @param interfaces  The interfaces to proxy
041     */
042    public JdkProxySource(ClassLoader classLoader, Class<?>[] interfaces) {
043        this.classLoader = classLoader;
044        // Defensive copy
045        this.interfaces = new Class<?>[interfaces.length];
046        System.arraycopy(interfaces, 0, this.interfaces, 0, interfaces.length);
047    }
048
049
050    @Override
051    public T createProxy(T pooledObject, UsageTracking<T> usageTracking) {
052        @SuppressWarnings("unchecked")
053        T proxy = (T) Proxy.newProxyInstance(classLoader, interfaces,
054                new JdkProxyHandler<T>(pooledObject, usageTracking));
055        return proxy;
056    }
057
058
059    @Override
060    public T resolveProxy(T proxy) {
061        @SuppressWarnings("unchecked")
062        JdkProxyHandler<T> jdkProxyHandler =
063                (JdkProxyHandler<T>) Proxy.getInvocationHandler(proxy);
064        T pooledObject = jdkProxyHandler.disableProxy();
065        return pooledObject;
066    }
067}