001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
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 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
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 io.jboot.aop.javassist;
017
018import com.jfinal.kit.LogKit;
019import com.jfinal.proxy.ProxyFactory;
020import javassist.util.proxy.MethodHandler;
021import javassist.util.proxy.ProxyObject;
022
023import java.util.function.Function;
024
025/**
026 * JbootCglibProxyFactory 用于扩展 cglib 的代理模式
027 *
028 * <pre>
029 * 配置方法:
030 * public void configConstant(Constants me) {
031 *     ProxyManager.me().setProxyFactory(new JbootJavassistProxyFactory());
032 * }
033 * </pre>
034 */
035public class JbootJavassistProxyFactory extends ProxyFactory {
036
037    /**
038     * 方便在单元测试的时候,可以对任意 class 进行 Mock
039     */
040    private static Function<Class<?>, MethodHandler> methodInterceptor = aClass -> new JbootJavassistHandler();
041
042    public static Function<Class<?>, MethodHandler> getMethodInterceptor() {
043        return methodInterceptor;
044    }
045
046    public static void setMethodInterceptor(Function<Class<?>, MethodHandler> methodInterceptor) {
047        JbootJavassistProxyFactory.methodInterceptor = methodInterceptor;
048    }
049
050    @Override
051    public <T> T get(Class<T> target) {
052        javassist.util.proxy.ProxyFactory factory = new javassist.util.proxy.ProxyFactory();
053        factory.setSuperclass(target);
054        final Class<?> proxyClass = factory.createClass();
055
056
057        T proxyObject = null;
058        try {
059            proxyObject = (T) proxyClass.newInstance();
060            ((ProxyObject) proxyObject).setHandler(methodInterceptor.apply(target));
061        } catch (Throwable e) {
062            LogKit.error(e.toString(), e);
063        }
064
065        return proxyObject;
066    }
067
068
069}
070
071
072