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.ProxyFactory; 022import org.apache.ibatis.javassist.util.proxy.ProxyObject; 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 036 private static final ModifyAttrsRecordProxyFactory INSTANCE = new ModifyAttrsRecordProxyFactory(); 037 038 public static ModifyAttrsRecordProxyFactory getInstance() { 039 return INSTANCE; 040 } 041 042 private ModifyAttrsRecordProxyFactory() { 043 } 044 045 @SuppressWarnings("unchecked") 046 public <T> T get(Class<T> target) { 047 Class<?> proxyClass = MapUtil.computeIfAbsent(CACHE, target, aClass -> { 048 Class<?>[] interfaces = Arrays.copyOf(target.getInterfaces(), target.getInterfaces().length + 1); 049 interfaces[interfaces.length - 1] = UpdateWrapper.class; 050 ProxyFactory factory = new ProxyFactory(); 051 factory.setSuperclass(target); 052 factory.setInterfaces(interfaces); 053 return factory.createClass(); 054 }); 055 056 T proxyObject; 057 try { 058 proxyObject = (T) ClassUtil.newInstance(proxyClass); 059 ((ProxyObject) proxyObject).setHandler(new ModifyAttrsRecordHandler()); 060 } catch (Exception e) { 061 throw FlexExceptions.wrap(e, "请为实体类 %s 添加公开的无参构造器!", target.getCanonicalName()); 062 } 063 return proxyObject; 064 } 065 066}