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 *
029 * @since 2.0
030 */
031public class JdkProxySource<T> implements ProxySource<T> {
032
033    private final ClassLoader classLoader;
034    private final Class<?>[] interfaces;
035
036    /**
037     * Constructs 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(final ClassLoader classLoader, final Class<?>[] interfaces) {
043        this.classLoader = classLoader;
044        // Defensive copy
045        this.interfaces = Arrays.copyOf(interfaces, interfaces.length);
046    }
047
048    @SuppressWarnings("unchecked") // Cast to T on return.
049    @Override
050    public T createProxy(final T pooledObject, final UsageTracking<T> usageTracking) {
051        return (T) Proxy.newProxyInstance(classLoader, interfaces,
052                new JdkProxyHandler<>(pooledObject, usageTracking));
053    }
054
055    @SuppressWarnings("unchecked")
056    @Override
057    public T resolveProxy(final T proxy) {
058        return ((JdkProxyHandler<T>) Proxy.getInvocationHandler(proxy)).disableProxy();
059    }
060
061    /**
062     * @since 2.4.3
063     */
064    @Override
065    public String toString() {
066        final StringBuilder builder = new StringBuilder();
067        builder.append("JdkProxySource [classLoader=");
068        builder.append(classLoader);
069        builder.append(", interfaces=");
070        builder.append(Arrays.toString(interfaces));
071        builder.append("]");
072        return builder.toString();
073    }
074}