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