我想创建一个中央记录器类来记录如下消息:
Couldn't find a record of type MyClass when searching for field MyField
目前,我有这段代码:
public static <T, A, B> String logNotFound(final Class<T> type, String field) {
return String.format(DATA_NOT_FOUND, type.getSimpleName(), field);
}
我这样调用它:
Optional<Person> person = findPersonByLastName("Smith");
if (person.isEmpty()) logNotFound(Person.class, "lastName");
但是,我不太喜欢将字符串传递给字段名称。我想将日志方法称为
logNotFound(Person.class, Person::getLastName)
传递 Function 作为参数。我期待这样的消息
Couldn't find a record of type Person when searching for field > Person::getLastName
有办法做到这一点吗?
最佳答案
似乎是 XY 问题:您实际上需要以方便的方式记录错误,但不知道如何在代码中引用类字段...有两种选择:
- Lombok :@FieldNameConstants -there are some issues
- 实现annotation processor这将为您的类生成元模型(或者如果您在 HBN 上,您可以使用现有的元模型:https://vladmihalcea.com/jpa-criteria-metamodel/)
关于java - 如何打印函数<A,B>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73142219/