0

Couple of disclaimers - first, I'm new to the functional side of Java, so I may be doing something very dumb. Secondly, there are probably easier ways to accomplish my goal in this context, but I'd still like to know if this method could be used, just for my own education. Thanks in advance!

So, I have a slightly ugly data structure representing a network, in which end-user workstations may or may not be reachable and have up-to-date information published to the network. I would like the network representation to have a function that looks like:

public <T>T getOrElse(String userName, Supplier<T> getterMethod, T absent)

The implementation for this method would search the network for a workstation with the given username; if one were found and deemed reliable, it would call the named access method on the workstation, and return the result to the original requester. If no such user were online, the network representation would return the default "absent" value instead. (As you might be able to guess, this is inspired by Optional's behavior.)

I have something wrong in the syntax, because when I try to call this with something like

String s = getOrElse("bob", Workstation::getSomeString, null);

I get complaints about static access to a non-static method. I'm also not sure what the syntax would be for applying the passed function to the workstation object, were it found in the network representation.

Is there a way to do this? I think it could be handled with reflections, but I would prefer to avoid using those.

Edward Peters
  • 3,623
  • 2
  • 16
  • 39

0 Answers0