经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MyBatis » 查看文章
Mybatis框架基础支持层——反射工具箱之Reflector&ReflectorFactory(3)
来源:cnblogs  作者:为了活的更像个人  时间:2019/1/21 9:28:06  对本文有异议

说明:Reflector是Mybatis反射工具的基础,每个Reflector对应一个类,在Reflector中封装有该类的元信息,

以及基于类信息的一系列反射应用封装API

  1. public class Reflector {
  2. private static final String[] EMPTY_STRING_ARRAY = new String[0];
  3. /**
  4. * 对应的类Class对象
  5. */
  6. private Class<?> type;
  7. /**
  8. * 类中可读属性的集合,就是存在相应的getter方法的属性
  9. */
  10. private String[] readablePropertyNames = EMPTY_STRING_ARRAY;
  11. /**
  12. * 类中可写属性的集合,就是存在相应的setter方法的属性
  13. */
  14. private String[] writeablePropertyNames = EMPTY_STRING_ARRAY;
  15. /**
  16. * 记录了属性相应的setter方法,key是属性名称,value是invoker对象,
  17. * invoker是对setter方法对应Method对象的封装
  18. */
  19. private Map<String, Invoker> setMethods = new HashMap<String, Invoker>();
  20. /**
  21. * 记录了属性相应的getter方法,key是属性名称,value是invoker对象,
  22. * invoker是对getter方法对应Method对象的封装
  23. */
  24. private Map<String, Invoker> getMethods = new HashMap<String, Invoker>();
  25. /**
  26. * 记录了属性相应的setter方法的参数值类型,key是属性名称,value是setter方法的参数值类型
  27. */
  28. private Map<String, Class<?>> setTypes = new HashMap<String, Class<?>>();
  29. /**
  30. * 记录了属性相应的getter方法的返回值类型,key是属性名称,value是getter方法的返回值类型
  31. */
  32. private Map<String, Class<?>> getTypes = new HashMap<String, Class<?>>();
  33. /**
  34. * 记录了默认构造方法
  35. */
  36. private Constructor<?> defaultConstructor;
  37. /**
  38. * 记录了所有属性名称的集合
  39. */
  40. private Map<String, String> caseInsensitivePropertyMap = new HashMap<String, String>();
  41. /**
  42. * 在Reflector构造方法中会指定某个类的Class对象,并填充上述集合
  43. */
  44. public Reflector(Class<?> clazz) {
  45. type = clazz;
  46. /**
  47. * 查找clazz的默认构造方法(无参构造)
  48. */
  49. addDefaultConstructor(clazz);
  50. /**
  51. * 处理clazz中的getter方法,填充getMethods集合和getTypes集合
  52. */
  53. addGetMethods(clazz);
  54. /**
  55. * 处理clazz中的setter方法,填充setMethods集合和setTypes集合
  56. */
  57. addSetMethods(clazz);
  58. /**
  59. * 处理没有getter/setter方法的字段
  60. */
  61. addFields(clazz);
  62. /**
  63. * 根据getMethods、setMethods集合,初始化可读/写属性名称的集合
  64. */
  65. readablePropertyNames = getMethods.keySet().toArray(new String[getMethods.keySet().size()]);
  66. writeablePropertyNames = setMethods.keySet().toArray(new String[setMethods.keySet().size()]);
  67. /**
  68. * 初始化caseInsensitivePropertyMap,其中记录了所有大写格式的属性名称
  69. */
  70. for (String propName : readablePropertyNames) {
  71. caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
  72. }
  73. for (String propName : writeablePropertyNames) {
  74. caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
  75. }
  76. }
  77. private void addDefaultConstructor(Class<?> clazz) {
  78. /**
  79. * 返回类中声明的所有构造函数Constructor,包括public、protected、default、private声明
  80. * 如果Class对象是一个接口、抽象类、数组类或void,则返回length=0的Constructor数组
  81. */
  82. Constructor<?>[] consts = clazz.getDeclaredConstructors();
  83. for (Constructor<?> constructor : consts) {
  84. if (constructor.getParameterTypes().length == 0) {
  85. if (canAccessPrivateMethods()) {
  86. try {
  87. constructor.setAccessible(true);
  88. } catch (Exception e) {
  89. // Ignored. This is only a final precaution, nothing we can do.
  90. }
  91. }
  92. if (constructor.isAccessible()) {
  93. this.defaultConstructor = constructor;
  94. }
  95. }
  96. }
  97. }
  98. private void addGetMethods(Class<?> cls) {
  99. Map<String, List<Method>> conflictingGetters = new HashMap<String, List<Method>>();
  100. /**
  101. * 获取当前类中所有的方法,包括自己、父类、父类的父类...,接口等
  102. */
  103. Method[] methods = getClassMethods(cls);
  104. for (Method method : methods) {
  105. String name = method.getName();
  106. if (name.startsWith("get") && name.length() > 3) {
  107. if (method.getParameterTypes().length == 0) {
  108. /**
  109. * PropertyNamer:
  110. * setter、getter方法名=>属性名称转换,和属性getter、setter方法判断
  111. */
  112. name = PropertyNamer.methodToProperty(name);
  113. addMethodConflict(conflictingGetters, name, method);
  114. }
  115. } else if (name.startsWith("is") && name.length() > 2) {
  116. if (method.getParameterTypes().length == 0) {
  117. name = PropertyNamer.methodToProperty(name);
  118. addMethodConflict(conflictingGetters, name, method);
  119. }
  120. }
  121. }
  122. //填充getMethods和getTypes集合
  123. resolveGetterConflicts(conflictingGetters);
  124. }
  125. private void resolveGetterConflicts(Map<String, List<Method>> conflictingGetters) {
  126. for (String propName : conflictingGetters.keySet()) {
  127. List<Method> getters = conflictingGetters.get(propName);
  128. Iterator<Method> iterator = getters.iterator();
  129. Method firstMethod = iterator.next();
  130. if (getters.size() == 1) {
  131. addGetMethod(propName, firstMethod);
  132. } else {
  133. Method getter = firstMethod;
  134. Class<?> getterType = firstMethod.getReturnType();
  135. while (iterator.hasNext()) {
  136. Method method = iterator.next();
  137. Class<?> methodType = method.getReturnType();
  138. if (methodType.equals(getterType)) {
  139. throw new ReflectionException("Illegal overloaded getter method with ambiguous type for property "
  140. + propName + " in class " + firstMethod.getDeclaringClass()
  141. + ". This breaks the JavaBeans " + "specification and can cause unpredictable results.");
  142. } else if (methodType.isAssignableFrom(getterType)) {
  143. // OK getter type is descendant
  144. } else if (getterType.isAssignableFrom(methodType)) {
  145. getter = method;
  146. getterType = methodType;
  147. } else {
  148. throw new ReflectionException("Illegal overloaded getter method with ambiguous type for property "
  149. + propName + " in class " + firstMethod.getDeclaringClass()
  150. + ". This breaks the JavaBeans " + "specification and can cause unpredictable results.");
  151. }
  152. }
  153. addGetMethod(propName, getter);
  154. }
  155. }
  156. }
  157. private void addGetMethod(String name, Method method) {
  158. if (isValidPropertyName(name)) {
  159. getMethods.put(name, new MethodInvoker(method));
  160. Type returnType = TypeParameterResolver.resolveReturnType(method, type);
  161. getTypes.put(name, typeToClass(returnType));
  162. }
  163. }
  164. private void addSetMethods(Class<?> cls) {
  165. Map<String, List<Method>> conflictingSetters = new HashMap<String, List<Method>>();
  166. Method[] methods = getClassMethods(cls);
  167. for (Method method : methods) {
  168. String name = method.getName();
  169. if (name.startsWith("set") && name.length() > 3) {
  170. if (method.getParameterTypes().length == 1) {
  171. name = PropertyNamer.methodToProperty(name);
  172. addMethodConflict(conflictingSetters, name, method);
  173. }
  174. }
  175. }
  176. resolveSetterConflicts(conflictingSetters);
  177. }
  178. private void addMethodConflict(Map<String, List<Method>> conflictingMethods, String name, Method method) {
  179. List<Method> list = conflictingMethods.get(name);
  180. if (list == null) {
  181. list = new ArrayList<Method>();
  182. conflictingMethods.put(name, list);
  183. }
  184. list.add(method);
  185. }
  186. private void resolveSetterConflicts(Map<String, List<Method>> conflictingSetters) {
  187. for (String propName : conflictingSetters.keySet()) {
  188. List<Method> setters = conflictingSetters.get(propName);
  189. Class<?> getterType = getTypes.get(propName);
  190. Method match = null;
  191. ReflectionException exception = null;
  192. for (Method setter : setters) {
  193. Class<?> paramType = setter.getParameterTypes()[0];
  194. if (paramType.equals(getterType)) {
  195. // should be the best match
  196. match = setter;
  197. break;
  198. }
  199. if (exception == null) {
  200. try {
  201. match = pickBetterSetter(match, setter, propName);
  202. } catch (ReflectionException e) {
  203. // there could still be the 'best match'
  204. match = null;
  205. exception = e;
  206. }
  207. }
  208. }
  209. if (match == null) {
  210. throw exception;
  211. } else {
  212. addSetMethod(propName, match);
  213. }
  214. }
  215. }
  216. private Method pickBetterSetter(Method setter1, Method setter2, String property) {
  217. if (setter1 == null) {
  218. return setter2;
  219. }
  220. Class<?> paramType1 = setter1.getParameterTypes()[0];
  221. Class<?> paramType2 = setter2.getParameterTypes()[0];
  222. if (paramType1.isAssignableFrom(paramType2)) {
  223. return setter2;
  224. } else if (paramType2.isAssignableFrom(paramType1)) {
  225. return setter1;
  226. }
  227. throw new ReflectionException("Ambiguous setters defined for property '" + property + "' in class '"
  228. + setter2.getDeclaringClass() + "' with types '" + paramType1.getName() + "' and '"
  229. + paramType2.getName() + "'.");
  230. }
  231. private void addSetMethod(String name, Method method) {
  232. if (isValidPropertyName(name)) {
  233. setMethods.put(name, new MethodInvoker(method));
  234. Type[] paramTypes = TypeParameterResolver.resolveParamTypes(method, type);
  235. setTypes.put(name, typeToClass(paramTypes[0]));
  236. }
  237. }
  238. private Class<?> typeToClass(Type src) {
  239. Class<?> result = null;
  240. if (src instanceof Class) {
  241. result = (Class<?>) src;
  242. } else if (src instanceof ParameterizedType) {
  243. result = (Class<?>) ((ParameterizedType) src).getRawType();
  244. } else if (src instanceof GenericArrayType) {
  245. Type componentType = ((GenericArrayType) src).getGenericComponentType();
  246. if (componentType instanceof Class) {
  247. result = Array.newInstance((Class<?>) componentType, 0).getClass();
  248. } else {
  249. Class<?> componentClass = typeToClass(componentType);
  250. result = Array.newInstance((Class<?>) componentClass, 0).getClass();
  251. }
  252. }
  253. if (result == null) {
  254. result = Object.class;
  255. }
  256. return result;
  257. }
  258. private void addFields(Class<?> clazz) {
  259. Field[] fields = clazz.getDeclaredFields();
  260. for (Field field : fields) {
  261. if (canAccessPrivateMethods()) {
  262. try {
  263. field.setAccessible(true);
  264. } catch (Exception e) {
  265. // Ignored. This is only a final precaution, nothing we can do.
  266. }
  267. }
  268. if (field.isAccessible()) {
  269. if (!setMethods.containsKey(field.getName())) {
  270. // issue #379 - removed the check for final because JDK 1.5 allows
  271. // modification of final fields through reflection (JSR-133). (JGB)
  272. // pr #16 - final static can only be set by the classloader
  273. int modifiers = field.getModifiers();
  274. if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))) {
  275. addSetField(field);
  276. }
  277. }
  278. if (!getMethods.containsKey(field.getName())) {
  279. addGetField(field);
  280. }
  281. }
  282. }
  283. //递归
  284. if (clazz.getSuperclass() != null) {
  285. addFields(clazz.getSuperclass());
  286. }
  287. }
  288. private void addSetField(Field field) {
  289. if (isValidPropertyName(field.getName())) {
  290. setMethods.put(field.getName(), new SetFieldInvoker(field));
  291. Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
  292. setTypes.put(field.getName(), typeToClass(fieldType));
  293. }
  294. }
  295. private void addGetField(Field field) {
  296. if (isValidPropertyName(field.getName())) {
  297. getMethods.put(field.getName(), new GetFieldInvoker(field));
  298. Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
  299. getTypes.put(field.getName(), typeToClass(fieldType));
  300. }
  301. }
  302. private boolean isValidPropertyName(String name) {
  303. return !(name.startsWith("$") || "serialVersionUID".equals(name) || "class".equals(name));
  304. }
  305. /*
  306. * This method returns an array containing all methods
  307. * declared in this class and any superclass.
  308. * We use this method, instead of the simpler Class.getMethods(),
  309. * because we want to look for private methods as well.
  310. *
  311. * @param cls The class
  312. * @return An array containing all methods in this class
  313. */
  314. private Method[] getClassMethods(Class<?> cls) {
  315. //key是方法签名(唯一标识,下文生成),value是Method对象
  316. Map<String, Method> uniqueMethods = new HashMap<String, Method>();
  317. Class<?> currentClass = cls;
  318. while (currentClass != null) {
  319. /**
  320. * currentClass.getDeclaredMethods()返回当前类或接口中所有被声明的方法,包括
  321. * public、protected、default、private,但是排除集成的方法
  322. *
  323. * 此方法是将当前类中非桥接(下文有介绍)方法填入uniqueMethods集合
  324. */
  325. addUniqueMethods(uniqueMethods, currentClass.getDeclaredMethods());
  326. // we also need to look for interface methods -
  327. // because the class may be abstract
  328. Class<?>[] interfaces = currentClass.getInterfaces();
  329. for (Class<?> anInterface : interfaces) {
  330. addUniqueMethods(uniqueMethods, anInterface.getMethods());
  331. }
  332. /**
  333. * Returns the {@code Class} representing the superclass of the entity
  334. * (class, interface, primitive type or void) represented by this
  335. * {@code Class}. If this {@code Class} represents either the
  336. * {@code Object} class, an interface, a primitive type, or void, then
  337. * null is returned. If this object represents an array class then the
  338. * {@code Class} object representing the {@code Object} class is
  339. * returned
  340. */
  341. currentClass = currentClass.getSuperclass();
  342. }
  343. Collection<Method> methods = uniqueMethods.values();
  344. return methods.toArray(new Method[methods.size()]);
  345. }
  346. private void addUniqueMethods(Map<String, Method> uniqueMethods, Method[] methods) {
  347. for (Method currentMethod : methods) {
  348. /**
  349. * 桥接方法是 JDK 1.5 引入泛型后,为了使Java的泛型方法生成的字节码和 1.5 版本前的字节码相兼容,
  350. * 由编译器自动生成的方法。我们可以通过Method.isBridge()方法来判断一个方法是否是桥接方法。
  351. */
  352. if (!currentMethod.isBridge()) {
  353. //获取当前方法的签名
  354. String signature = getSignature(currentMethod);
  355. // check to see if the method is already known
  356. // if it is known, then an extended class must have
  357. // overridden a method
  358. if (!uniqueMethods.containsKey(signature)) {
  359. if (canAccessPrivateMethods()) {
  360. try {
  361. currentMethod.setAccessible(true);
  362. } catch (Exception e) {
  363. // Ignored. This is only a final precaution, nothing we can do.
  364. }
  365. }
  366. uniqueMethods.put(signature, currentMethod);
  367. }
  368. }
  369. }
  370. }
  371. /**
  372. * 获取一个方法的签名,根据方法的返回值、方法、方法参数构建一个签名
  373. */
  374. private String getSignature(Method method) {
  375. StringBuilder sb = new StringBuilder();
  376. Class<?> returnType = method.getReturnType();
  377. if (returnType != null) {
  378. sb.append(returnType.getName()).append('#');
  379. }
  380. sb.append(method.getName());
  381. Class<?>[] parameters = method.getParameterTypes();
  382. for (int i = 0; i < parameters.length; i++) {
  383. if (i == 0) {
  384. sb.append(':');
  385. } else {
  386. sb.append(',');
  387. }
  388. sb.append(parameters[i].getName());
  389. }
  390. return sb.toString();
  391. }
  392. private static boolean canAccessPrivateMethods() {
  393. try {
  394. //java安全管理器具体细节,可看博客中另一篇介绍
  395. SecurityManager securityManager = System.getSecurityManager();
  396. if (null != securityManager) {
  397. securityManager.checkPermission(new ReflectPermission("suppressAccessChecks"));
  398. }
  399. } catch (SecurityException e) {
  400. return false;
  401. }
  402. return true;
  403. }
  404. /*
  405. * Gets the name of the class the instance provides information for
  406. *
  407. * @return The class name
  408. */
  409. public Class<?> getType() {
  410. return type;
  411. }
  412. public Constructor<?> getDefaultConstructor() {
  413. if (defaultConstructor != null) {
  414. return defaultConstructor;
  415. } else {
  416. throw new ReflectionException("There is no default constructor for " + type);
  417. }
  418. }
  419. public boolean hasDefaultConstructor() {
  420. return defaultConstructor != null;
  421. }
  422. public Invoker getSetInvoker(String propertyName) {
  423. Invoker method = setMethods.get(propertyName);
  424. if (method == null) {
  425. throw new ReflectionException("There is no setter for property named '" + propertyName + "' in '" + type + "'");
  426. }
  427. return method;
  428. }
  429. public Invoker getGetInvoker(String propertyName) {
  430. Invoker method = getMethods.get(propertyName);
  431. if (method == null) {
  432. throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + type + "'");
  433. }
  434. return method;
  435. }
  436. /*
  437. * Gets the type for a property setter
  438. *
  439. * @param propertyName - the name of the property
  440. * @return The Class of the propery setter
  441. */
  442. public Class<?> getSetterType(String propertyName) {
  443. Class<?> clazz = setTypes.get(propertyName);
  444. if (clazz == null) {
  445. throw new ReflectionException("There is no setter for property named '" + propertyName + "' in '" + type + "'");
  446. }
  447. return clazz;
  448. }
  449. /*
  450. * Gets the type for a property getter
  451. *
  452. * @param propertyName - the name of the property
  453. * @return The Class of the propery getter
  454. */
  455. public Class<?> getGetterType(String propertyName) {
  456. Class<?> clazz = getTypes.get(propertyName);
  457. if (clazz == null) {
  458. throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + type + "'");
  459. }
  460. return clazz;
  461. }
  462. /*
  463. * Gets an array of the readable properties for an object
  464. *
  465. * @return The array
  466. */
  467. public String[] getGetablePropertyNames() {
  468. return readablePropertyNames;
  469. }
  470. /*
  471. * Gets an array of the writeable properties for an object
  472. *
  473. * @return The array
  474. */
  475. public String[] getSetablePropertyNames() {
  476. return writeablePropertyNames;
  477. }
  478. /*
  479. * Check to see if a class has a writeable property by name
  480. *
  481. * @param propertyName - the name of the property to check
  482. * @return True if the object has a writeable property by the name
  483. */
  484. public boolean hasSetter(String propertyName) {
  485. return setMethods.keySet().contains(propertyName);
  486. }
  487. /*
  488. * Check to see if a class has a readable property by name
  489. *
  490. * @param propertyName - the name of the property to check
  491. * @return True if the object has a readable property by the name
  492. */
  493. public boolean hasGetter(String propertyName) {
  494. return getMethods.keySet().contains(propertyName);
  495. }
  496. public String findPropertyName(String name) {
  497. return caseInsensitivePropertyMap.get(name.toUpperCase(Locale.ENGLISH));
  498. }
  499. }

ReflectorFactory接口主要实现了对Reflector对象的创建和缓存,Mybatis为该接口提供了仅有的一个实现类DefaultReflectorFactory:

 

  1. public interface ReflectorFactory {
  2. /**
  3. * 检测ReflectorFactory对象是否启用缓存Reflector功能
  4. */
  5. boolean isClassCacheEnabled();
  6. /**
  7. * 设置ReflectorFactory对象是否启用缓存Reflector功能
  8. */
  9. void setClassCacheEnabled(boolean classCacheEnabled);
  10. /**
  11. * 创建指定Class对象对应的Reflector,如果缓存有,就从缓存取,否则新建一个
  12. */
  13. Reflector findForClass(Class<?> type);
  14. }

 

  1. public class DefaultReflectorFactory implements ReflectorFactory {
  2. /**
  3. * 默认启用缓存Reflector的功能
  4. */
  5. private boolean classCacheEnabled = true;
  6. /**
  7. * 缓存Reflector的数据结构,key[Class对象],value[Class对应的Reflector对象]
  8. */
  9. private final ConcurrentMap<Class<?>, Reflector> reflectorMap = new ConcurrentHashMap<Class<?>, Reflector>();
  10. public DefaultReflectorFactory() {
  11. }
  12. @Override
  13. public boolean isClassCacheEnabled() {
  14. return classCacheEnabled;
  15. }
  16. @Override
  17. public void setClassCacheEnabled(boolean classCacheEnabled) {
  18. this.classCacheEnabled = classCacheEnabled;
  19. }
  20. @Override
  21. public Reflector findForClass(Class<?> type) {
  22. if (classCacheEnabled) {
  23. // synchronized (type) removed see issue #461
  24. Reflector cached = reflectorMap.get(type);
  25. if (cached == null) {
  26. cached = new Reflector(type);
  27. reflectorMap.put(type, cached);
  28. }
  29. return cached;
  30. } else {
  31. return new Reflector(type);
  32. }
  33. }
  34. }

 

原文链接:http://www.cnblogs.com/wly1-6/p/10284149.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号