001/*
002 *  Copyright (c) 2022-2025, 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.exception.FlexExceptions;
019import com.mybatisflex.core.util.ClassUtil;
020import com.mybatisflex.core.util.MapUtil;
021import org.apache.ibatis.javassist.util.proxy.Proxy;
022import org.apache.ibatis.javassist.util.proxy.ProxyFactory;
023import org.apache.ibatis.javassist.util.proxy.ProxyObject;
024
025import java.util.Arrays;
026import java.util.Map;
027import java.util.concurrent.ConcurrentHashMap;
028
029
030/**
031 * @author michael
032 */
033public class ModifyAttrsRecordProxyFactory {
034
035    protected static final Map<Class<?>, Class<?>> CACHE = new ConcurrentHashMap<>();
036
037    private static final ModifyAttrsRecordProxyFactory INSTANCE = new ModifyAttrsRecordProxyFactory();
038
039    public static ModifyAttrsRecordProxyFactory getInstance() {
040        return INSTANCE;
041    }
042
043    private ModifyAttrsRecordProxyFactory() {
044    }
045
046    @SuppressWarnings("unchecked")
047    public <T> T get(Class<T> target) {
048        Class<?> proxyClass = MapUtil.computeIfAbsent(CACHE, target, aClass -> {
049            Class<?>[] interfaces = Arrays.copyOf(target.getInterfaces(), target.getInterfaces().length + 1);
050            interfaces[interfaces.length - 1] = UpdateWrapper.class;
051            ProxyFactory factory = new ProxyFactory();
052            factory.setSuperclass(target);
053            factory.setInterfaces(interfaces);
054            return factory.createClass();
055        });
056
057        T proxyObject;
058        try {
059            proxyObject = (T) ClassUtil.newInstance(proxyClass);
060        } catch (Exception e) {
061            throw FlexExceptions.wrap(e, "请为实体类 %s 添加公开的无参构造器!", target.getCanonicalName());
062        }
063        if (proxyObject instanceof ProxyObject) {
064            ((ProxyObject) proxyObject).setHandler(new ModifyAttrsRecordHandler());
065        } else if (proxyObject instanceof Proxy) {
066            ((Proxy) proxyObject).setHandler(new ModifyAttrsRecordHandler());
067        } else {
068            throw FlexExceptions.wrap("为实体类 %s 设置字段更新处理器时出错,获取的实体类代理对象既不是 ProxyObject 的实例,也不是 Proxy 的实例", target.getCanonicalName());
069        }
070        return proxyObject;
071    }
072
073}