001/*
002 *  Copyright (c) 2022-2023, Mybatis-Flex (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 com.mybatisflex.core.update;
017
018import com.mybatisflex.core.util.ClassUtil;
019import org.apache.ibatis.javassist.util.proxy.ProxyFactory;
020import org.apache.ibatis.javassist.util.proxy.ProxyObject;
021import org.apache.ibatis.logging.LogFactory;
022import org.apache.ibatis.util.MapUtil;
023
024import java.util.Arrays;
025import java.util.Map;
026import java.util.concurrent.ConcurrentHashMap;
027
028
029/**
030 * @author michael
031 */
032public class ModifyAttrsRecordProxyFactory {
033
034    protected static final Map<Class<?>, Class<?>> CACHE = new ConcurrentHashMap<>();
035    private static final ModifyAttrsRecordProxyFactory INSTANCE = new ModifyAttrsRecordProxyFactory();
036
037    public static ModifyAttrsRecordProxyFactory getInstance() {
038        return INSTANCE;
039    }
040
041    private ModifyAttrsRecordProxyFactory() {
042    }
043
044    public <T> T get(Class<T> target) {
045        Class<?> proxyClass = MapUtil.computeIfAbsent(CACHE, target, aClass -> {
046            ProxyFactory factory = new ProxyFactory();
047            factory.setSuperclass(target);
048
049            Class<?>[] interfaces = Arrays.copyOf(target.getInterfaces(), target.getInterfaces().length + 1);
050            interfaces[interfaces.length - 1] = UpdateWrapper.class;
051            factory.setInterfaces(interfaces);
052
053            return factory.createClass();
054        });
055
056        T proxyObject = null;
057        try {
058            proxyObject = (T) ClassUtil.newInstance(proxyClass);
059            ((ProxyObject) proxyObject).setHandler(new ModifyAttrsRecordHandler());
060        } catch (Exception e) {
061            LogFactory.getLog(ModifyAttrsRecordProxyFactory.class).error(e.toString(), e);
062        }
063
064        return proxyObject;
065    }
066}
067
068
069