Home > Software engineering >  How to print a Function<A,B>?
How to print a Function<A,B>?

Time:07-28

I would like to create a central logger class that logs messages like:

Couldn't find a record of type MyClass when searching for field MyField

Currently, I have this piece of code:

public static <T, A, B> String logNotFound(final Class<T> type, String field) {
    return String.format(DATA_NOT_FOUND, type.getSimpleName(), field);
}

And I call it like:

Optional<Person> person = findPersonByLastName("Smith");
if (person.isEmpty()) logNotFound(Person.class, "lastName");

However, I don't quite like passing a string to the field name. I would like to call the log method as

logNotFound(Person.class, Person::getLastName)

passing a Function<A,B> as parameter. I expect a message like

Couldn't find a record of type Person when searching for field > Person::getLastName

Is there a way to do this?

CodePudding user response:

seems to be XY problem: you actually need to log errors in convenient way, but does not know how to refer class fields in code... There are two options:

  1. lombok: @FieldNameConstants - there are some issues
  2. implement annotation processor which will generate metamodel for your classes (or if you are on HBN you may use existing one: https://vladmihalcea.com/jpa-criteria-metamodel/)

CodePudding user response:

It is possible, use (or analyze the source code and implement it in your way) safety-mirror library:

assertEquals("isEmpty", Fun.getName(String::isEmpty));

Here you read more details - Printing debug info on errors with java 8 lambda expressions

  •  Tags:  
  • java
  • Related