Java获取实体类字段名

it2023-01-25  50

参考:https://www.cnblogs.com/liangweiping/archive/2020/04/28/12792418.html

/** * 使Function获取序列化能力 */ @FunctionalInterface public interface SFunction<T, R> extends Function<T, R>, Serializable { }

工具类

public class SFunctionUtil { public static <T> String getName(SFunction<T, ?> fn) { // 从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()); return fieldName; } }

使用

String id= SFunctionUtil.getName(Bean::getId); // "id"
最新回复(0)