歡迎您光臨本站 註冊首頁

Java8通過Function獲取字段名的步驟

←手機掃碼閱讀     火星人 @ 2020-04-28 , reply:0

摘要:Java8通過Function獲取字段名,解決硬編碼,效果類似於mybatis-plus的LambdaQueryWrapper。

本文總共三個步驟:

1、使Function獲取序列化能力;

2、通過SFunction獲取字段名;

3、建一些業務代碼進行測試;

使Function獲取序列化能力

import java.io.Serializable; import java.util.function.Function; /** * 使Function獲取序列化能力 */ @FunctionalInterface public interface SFunction

extends Function, Serializable { }

通過SFunction獲取字段名

import java.lang.invoke.SerializedLambda; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class ColumnUtil { public staticString getName(SFunctionfn) { // 從function取出序列化方法 Method writeReplaceMethod; try { writeReplaceMethod = fn.getClass().getDeclaredMethod("writeReplace"); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } // 從序列化方法取出序列化的lambda信息 boolean isAccessible = writeReplaceMethod.isAccessible(); writeReplaceMethod.setAccessible(true); SerializedLambda serializedLambda; try { serializedLambda = (SerializedLambda) writeReplaceMethod.invoke(fn); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } writeReplaceMethod.setAccessible(isAccessible); // 從lambda信息取出method、field、class等 String fieldName = serializedLambda.getImplMethodName().substring("get".length()); fieldName = fieldName.replaceFirst(fieldName.charAt(0) + "", (fieldName.charAt(0) + "").toLowerCase()); Field field; try { field = Class.forName(serializedLambda.getImplClass().replace("/", ".")).getDeclaredField(fieldName); } catch (ClassNotFoundException | NoSuchFieldException e) { throw new RuntimeException(e); } // 從field取出字段名,可以根據實際情況調整 TableField tableField = field.getAnnotation(TableField.class); if (tableField != null && tableField.value().length() > 0) { return tableField.value(); } else { return fieldName.replaceAll("[A-Z]", "_$0").toLowerCase(); } } }

建一些業務代碼進行測試

import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 字段名註解。測試用 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface TableField { String value() default ""; }

import java.io.Serializable; /** * 用戶實體類。測試用 */ public class User implements Serializable { private String loginName; @TableField("nick") private String nickName; public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } }

/** * 測試用 */ public class Test { public static void main(String[] args) { System.out.println("字段名:" + ColumnUtil.getName(User::getLoginName)); System.out.println("字段名:" + ColumnUtil.getName(User::getNickName)); } }


字段名:login_name

字段名:nick



[火星人 ] Java8通過Function獲取字段名的步驟已經有217次圍觀

http://coctec.com/docs/java/show-post-232022.html