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
018
019import org.apache.ibatis.javassist.util.proxy.ProxyObject;
020
021import java.lang.reflect.*;
022import java.util.ArrayList;
023import java.util.Arrays;
024import java.util.List;
025import java.util.function.Predicate;
026
027/**
028 * 类实例创建者创建者
029 *
030 * @author michael
031 * @date 17/3/21
032 */
033@SuppressWarnings("unchecked")
034public class ClassUtil {
035
036    private ClassUtil() {
037    }
038
039    private static final String[] OBJECT_METHODS = new String[]{
040        "toString",
041        "getClass",
042        "equals",
043        "hashCode",
044        "wait",
045        "notify",
046        "notifyAll",
047        "clone",
048        "finalize"
049    };
050
051    //proxy frameworks
052    private static final List<String> PROXY_CLASS_NAMES = Arrays.asList("net.sf.cglib.proxy.Factory"
053        // cglib
054        , "org.springframework.cglib.proxy.Factory"
055
056        // javassist
057        , "javassist.util.proxy.ProxyObject"
058        , "org.apache.ibatis.javassist.util.proxy.ProxyObject");
059    private static final String ENHANCER_BY = "$$EnhancerBy";
060    private static final String JAVASSIST_BY = "_$$_";
061
062    public static boolean isProxy(Class<?> clazz) {
063        for (Class<?> cls : clazz.getInterfaces()) {
064            if (PROXY_CLASS_NAMES.contains(cls.getName())) {
065                return true;
066            }
067        }
068        //java proxy
069        return Proxy.isProxyClass(clazz);
070    }
071
072    public static <T> Class<T> getUsefulClass(Class<T> clazz) {
073
074        if (ProxyObject.class.isAssignableFrom(clazz)) {
075            return (Class<T>) clazz.getSuperclass();
076        }
077
078        if (isProxy(clazz)) {
079            return getJdkProxySuperClass(clazz);
080        }
081
082        //ControllerTest$ServiceTest$$EnhancerByGuice$$40471411#hello   -------> Guice
083        //com.demo.blog.Blog$$EnhancerByCGLIB$$69a17158  ----> CGLIB
084        //io.jboot.test.app.TestAppListener_$$_jvstb9f_0 ------> javassist
085        final String name = clazz.getName();
086        if (name.contains(ENHANCER_BY) || name.contains(JAVASSIST_BY)) {
087            return (Class<T>) clazz.getSuperclass();
088        }
089
090        return clazz;
091    }
092
093
094    public static Class<?> getWrapType(Class<?> clazz) {
095        if (clazz == null || !clazz.isPrimitive()) {
096            return clazz;
097        }
098        if (clazz == Integer.TYPE) {
099            return Integer.class;
100        } else if (clazz == Long.TYPE) {
101            return Long.class;
102        } else if (clazz == Boolean.TYPE) {
103            return Boolean.class;
104        } else if (clazz == Float.TYPE) {
105            return Float.class;
106        } else if (clazz == Double.TYPE) {
107            return Double.class;
108        } else if (clazz == Short.TYPE) {
109            return Short.class;
110        } else if (clazz == Character.TYPE) {
111            return Character.class;
112        } else if (clazz == Byte.TYPE) {
113            return Byte.class;
114        } else if (clazz == Void.TYPE) {
115            return Void.class;
116        }
117        return clazz;
118    }
119
120
121    public static boolean isArray(Class<?> clazz) {
122        return clazz.isArray()
123            || clazz == int[].class
124            || clazz == long[].class
125            || clazz == short[].class
126            || clazz == float[].class
127            || clazz == double[].class;
128    }
129
130    public static boolean canInstance(int mod) {
131        return !Modifier.isAbstract(mod) || !Modifier.isInterface(mod);
132    }
133
134
135    public static <T> T newInstance(Class<T> clazz) {
136        try {
137            Constructor<?> defaultConstructor = null;
138            Constructor<?> otherConstructor = null;
139
140            Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
141            for (Constructor<?> constructor : declaredConstructors) {
142                if (constructor.getParameterCount() == 0 && Modifier.isPublic(constructor.getModifiers())) {
143                    defaultConstructor = constructor;
144                } else if (Modifier.isPublic(constructor.getModifiers())) {
145                    otherConstructor = constructor;
146                }
147            }
148            if (defaultConstructor != null) {
149                return (T) defaultConstructor.newInstance();
150            } else if (otherConstructor != null) {
151                Class<?>[] parameterTypes = otherConstructor.getParameterTypes();
152                Object[] parameters = new Object[parameterTypes.length];
153                for (int i = 0; i < parameterTypes.length; i++) {
154                    if (parameterTypes[i].isPrimitive()) {
155                        parameters[i] = ConvertUtil.getPrimitiveDefaultValue(parameterTypes[i]);
156                    } else {
157                        parameters[i] = null;
158                    }
159                }
160                return (T) otherConstructor.newInstance(parameters);
161            }
162            // 没有任何构造函数的情况下,去查找 static 工厂方法,满足 lombok 注解的需求
163            else {
164                Method factoryMethod = ClassUtil.getFirstMethod(clazz, m -> m.getParameterCount() == 0
165                    && clazz == m.getReturnType()
166                    && Modifier.isPublic(m.getModifiers())
167                    && Modifier.isStatic(m.getModifiers()));
168                if (factoryMethod != null) {
169                    return (T) factoryMethod.invoke(null);
170                }
171            }
172            throw new IllegalArgumentException("the class \"" + clazz.getName() + "\" has no constructor.");
173        } catch (Exception e) {
174            throw new RuntimeException("Can not newInstance class: " + clazz.getName());
175        }
176    }
177
178
179    public static <T> T newInstance(Class<T> clazz, Object... paras) {
180        try {
181            Constructor<?>[] constructors = clazz.getDeclaredConstructors();
182            for (Constructor<?> constructor : constructors) {
183                if (isMatchedParas(constructor, paras)) {
184                    Object ret = constructor.newInstance(paras);
185                    return (T) ret;
186                }
187            }
188            throw new IllegalArgumentException("Can not find constructor by paras: \"" + Arrays.toString(paras) + "\" in class[" + clazz.getName() + "]");
189        } catch (Exception e) {
190            e.printStackTrace();
191        }
192
193        return null;
194    }
195
196
197    private static boolean isMatchedParas(Constructor<?> constructor, Object[] paras) {
198        if (constructor.getParameterCount() == 0) {
199            return paras == null || paras.length == 0;
200        }
201
202        if (constructor.getParameterCount() > 0
203            && (paras == null || paras.length != constructor.getParameterCount())) {
204            return false;
205        }
206
207        Class<?>[] parameterTypes = constructor.getParameterTypes();
208        for (int i = 0; i < parameterTypes.length; i++) {
209            Class<?> parameterType = parameterTypes[i];
210            Object paraObject = paras[i];
211            if (paraObject != null && !parameterType.isAssignableFrom(paraObject.getClass())) {
212                return false;
213            }
214        }
215
216        return true;
217    }
218
219
220    public static List<Field> getAllFields(Class<?> clazz) {
221        List<Field> fields = new ArrayList<>();
222        doGetFields(clazz, fields, null, false);
223        return fields;
224    }
225
226    public static List<Field> getAllFields(Class<?> clazz, Predicate<Field> predicate) {
227        List<Field> fields = new ArrayList<>();
228        doGetFields(clazz, fields, predicate, false);
229        return fields;
230    }
231
232    public static Field getFirstField(Class<?> clazz, Predicate<Field> predicate) {
233        List<Field> fields = new ArrayList<>();
234        doGetFields(clazz, fields, predicate, true);
235        return fields.isEmpty() ? null : fields.get(0);
236    }
237
238    private static void doGetFields(Class<?> clazz, List<Field> fields, Predicate<Field> predicate, boolean firstOnly) {
239        if (clazz == null || clazz == Object.class) {
240            return;
241        }
242
243        Field[] declaredFields = clazz.getDeclaredFields();
244        for (Field declaredField : declaredFields) {
245            if (predicate == null || predicate.test(declaredField)) {
246                fields.add(declaredField);
247                if (firstOnly) {
248                    break;
249                }
250            }
251        }
252
253        if (firstOnly && !fields.isEmpty()) {
254            return;
255        }
256
257        doGetFields(clazz.getSuperclass(), fields, predicate, firstOnly);
258    }
259
260    public static List<Method> getAllMethods(Class<?> clazz) {
261        List<Method> methods = new ArrayList<>();
262        doGetMethods(clazz, methods, null, false);
263        return methods;
264    }
265
266    public static List<Method> getAllMethods(Class<?> clazz, Predicate<Method> predicate) {
267        List<Method> methods = new ArrayList<>();
268        doGetMethods(clazz, methods, predicate, false);
269        return methods;
270    }
271
272    public static Method getAnyMethod(Class<?> clazz, String... methodNames) {
273        return getFirstMethod(clazz, method -> ArrayUtil.contains(methodNames, method.getName()));
274    }
275
276    public static Method getFirstMethod(Class<?> clazz, Predicate<Method> predicate) {
277        List<Method> methods = new ArrayList<>();
278        doGetMethods(clazz, methods, predicate, true);
279        return methods.isEmpty() ? null : methods.get(0);
280    }
281
282
283    private static void doGetMethods(Class<?> clazz, List<Method> methods, Predicate<Method> predicate, boolean firstOnly) {
284        if (clazz == null || clazz == Object.class) {
285            return;
286        }
287
288        Method[] declaredMethods = clazz.getDeclaredMethods();
289        for (Method method : declaredMethods) {
290            if (predicate == null || predicate.test(method)) {
291                methods.add(method);
292                if (firstOnly) {
293                    break;
294                }
295            }
296        }
297
298        if (firstOnly && !methods.isEmpty()) {
299            return;
300        }
301
302        doGetMethods(clazz.getSuperclass(), methods, predicate, firstOnly);
303    }
304
305
306    private static <T> Class<T> getJdkProxySuperClass(Class<T> clazz) {
307        final Class<?> proxyClass = Proxy.getProxyClass(clazz.getClassLoader(), clazz.getInterfaces());
308        return (Class<T>) proxyClass.getInterfaces()[0];
309    }
310
311
312    public static boolean isGetterMethod(Method method, String property) {
313        String methodName = method.getName();
314        if (methodName.startsWith("get") && methodName.length() > 3) {
315            return StringUtil.firstCharToUpperCase(property).equals(methodName.substring(3));
316        } else if (methodName.startsWith("is") && methodName.length() > 2) {
317            return StringUtil.firstCharToUpperCase(property).equals(methodName.substring(2));
318        } else {
319            return false;
320        }
321    }
322
323    public static boolean isObjectMethod(String methodName) {
324        return ArrayUtil.contains(OBJECT_METHODS, methodName);
325    }
326
327}