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;
020import java.util.Arrays;
021
022import org.apache.commons.pool2.UsageTracking;
023
024/**
025 * Provides proxy objects using Java reflection.
026 *
027 * @param <T> type of the pooled object to be proxied
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     * Constructs a new proxy source for the given interfaces.
037     *
038     * @param classLoader The class loader with which to create the proxy
039     * @param interfaces  The interfaces to proxy
040     */
041    public JdkProxySource(final ClassLoader classLoader, final Class<?>[] interfaces) {
042        this.classLoader = classLoader;
043        // Defensive copy
044        this.interfaces = Arrays.copyOf(interfaces, interfaces.length);
045    }
046
047    @SuppressWarnings("unchecked") // Cast to T on return.
048    @Override
049    public T createProxy(final T pooledObject, final UsageTracking<T> usageTracking) {
050        return (T) Proxy.newProxyInstance(classLoader, interfaces,
051                new JdkProxyHandler<>(pooledObject, usageTracking));
052    }
053
054    @SuppressWarnings("unchecked")
055    @Override
056    public T resolveProxy(final T proxy) {
057        return ((JdkProxyHandler<T>) Proxy.getInvocationHandler(proxy)).disableProxy();
058    }
059
060    /**
061     * @since 2.4.3
062     */
063    @Override
064    public String toString() {
065        final StringBuilder builder = new StringBuilder();
066        builder.append("JdkProxySource [classLoader=");
067        builder.append(classLoader);
068        builder.append(", interfaces=");
069        builder.append(Arrays.toString(interfaces));
070        builder.append("]");
071        return builder.toString();
072    }
073}