mybatis-plus
mybatis-plus copied to clipboard
可以根据fieldname生成SFunction吗
当前使用版本(必填,否则不予处理)
3.5.1
请问怎么样根据fieldname生成SFunction 根据SFunction获取fieldname网上有很多 怎么根据fieldname生成SFunction呢
比如我有一个Person类 里面有name属性 我怎么根据name这个字符串和Person这个class 获取SFunction
很棒的问题
public static SFunction getSFunction(Class<?> entityClass, String fieldName) { if (functionMap.containsKey(entityClass.getName() + fieldName)) { return (SFunction)functionMap.get(entityClass.getName() + fieldName); } else { Field field = getDeclaredField(entityClass, fieldName); if (field == null) { throw ExceptionUtils.mpe("This class %s is not have field %s ", new Object[]{entityClass.getName(), fieldName}); } else { SFunction func = null; MethodHandles.Lookup lookup = MethodHandles.lookup(); MethodType methodType = MethodType.methodType(field.getType(), entityClass); String getFunName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
try {
CallSite site = LambdaMetafactory.altMetafactory(lookup, "invoke", MethodType.methodType(SFunction.class), methodType, lookup.findVirtual(entityClass, getFunName, MethodType.methodType(field.getType())), methodType, 1);
func = site.getTarget().invokeExact();
functionMap.put(entityClass.getName() + field, func);
return func;
} catch (Throwable var9) {
throw ExceptionUtils.mpe("This class %s is not have method %s ", new Object[]{entityClass.getName(), getFunName});
}
}
}
}
参考这里面的改一下把。 完整代码在:https://gitee.com/baomidou/mybatis-plus-advance/blob/master/src/main/java/com/baomidou/mybatisplus/advance/injector/FuntionTools.java
见:https://gitee.com/baomidou/mybatis-plus/blob/3.0/mybatis-plus-core/src/test/java/com/baomidou/mybatisplus/test/toolkit/LambdaUtilsTest.java#L49