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.util;
017
018import com.mybatisflex.core.javassist.ModifyAttrsRecordProxyFactory;
019import org.apache.ibatis.reflection.DefaultReflectorFactory;
020import org.apache.ibatis.reflection.Reflector;
021import org.apache.ibatis.reflection.ReflectorFactory;
022
023public class UpdateEntity {
024
025    private static ReflectorFactory reflectorFactory = new DefaultReflectorFactory();
026
027
028
029    public static <T> T wrap(Class<T> clazz) {
030        return ModifyAttrsRecordProxyFactory.getInstance().get(clazz);
031    }
032
033
034
035    public static <T> T ofNotNull(T entity) {
036        Class<?> usefulClass = ClassUtil.getUsefulClass(entity.getClass());
037
038        T newEntity = (T) wrap(usefulClass);
039
040        Reflector reflector = reflectorFactory.findForClass(usefulClass);
041        String[] propertyNames = reflector.getGetablePropertyNames();
042
043        for (String propertyName : propertyNames) {
044            try {
045                Object value = reflector.getGetInvoker(propertyName)
046                        .invoke(entity, null);
047                if (value != null) {
048                    reflector.getSetInvoker(propertyName).invoke(newEntity, new Object[]{value});
049                }
050            } catch (Exception e) {
051                //ignore();
052            }
053        }
054
055        return newEntity;
056    }
057
058
059}