Class

  1. @FunctionalInterface
  2. public interface CacheFunction extends Serializable {
  3. /**
  4. * 这里只接收无参方法
  5. *
  6. * @return
  7. */
  8. Object apply();
  9. /**
  10. * 这个方法返回的SerializedLambda是重点
  11. *
  12. * @return
  13. * @throws Exception
  14. */
  15. default SerializedLambda getSerializedLambda() throws Exception {
  16. SerializedLambda obj = CacheCommonUtils.cacheFunctionClassMap.get(this.getClass().getName());
  17. if (null == obj) {
  18. //writeReplace改了好像会报异常
  19. Method write = this.getClass().getDeclaredMethod("writeReplace");
  20. write.setAccessible(true);
  21. obj = (SerializedLambda) write.invoke(this);
  22. CacheCommonUtils.cacheFunctionClassMap.put(this.getClass().getName(), obj);
  23. }
  24. return obj;
  25. }
  26. /**
  27. * getImplClass
  28. *
  29. * @return
  30. */
  31. default String getImplClass() {
  32. try {
  33. return getSerializedLambda().getImplClass();
  34. } catch (Exception e) {
  35. return null;
  36. }
  37. }
  38. /**
  39. * getImplMethodName
  40. *
  41. * @return
  42. */
  43. default String getImplMethodName() {
  44. try {
  45. return getSerializedLambda().getImplMethodName();
  46. } catch (Exception e) {
  47. return null;
  48. }
  49. }
  50. /**
  51. * 获取方法名称
  52. *
  53. * @return
  54. */
  55. default String fnToFnName() {
  56. try {
  57. String[] split = getSerializedLambda().getImplMethodName().split("\\$", 3);
  58. return split[1];
  59. } catch (Exception e) {
  60. }
  61. return "";
  62. }
  63. /**
  64. * 获取方法参数,反射已缓存,每次拿到的参数都是第一次调用时的
  65. *
  66. * @return
  67. */
  68. @Deprecated
  69. default List<Object> getFuncFields() {
  70. try {
  71. SerializedLambda serializedLambda = getSerializedLambda();
  72. List<Object> list = new ArrayList<>(serializedLambda.getCapturedArgCount());
  73. for (int i = 0; i < serializedLambda.getCapturedArgCount(); i++) {
  74. if (!serializedLambda.getCapturedArg(i).toString().startsWith("com.")) {
  75. list.add(serializedLambda.getCapturedArg(i));
  76. }
  77. }
  78. return list;
  79. } catch (Exception e) {
  80. }
  81. return new ArrayList<>();
  82. }
  83. }

介绍

在Lcache中,对cache的封装都是通过CacheFunction进行传递执行,大量的场景需要获取方法名称,单纯的反射即可获取;但是性能太低,因此通过Map将反射对象进行缓存,大大提高性能
Map cacheFunctionClassMap = new ConcurrentHashMap<>();

使用

  1. String commands = function.fnToFnName();
  2. //通过数据结构Util还可获取方法的数据结构等信息
  3. String dataStructure = CommandsDataTypeUtil.getCommandsDataType(commands).name()