0

I'm trying to create a method that puts a Function's results in to a Consumer you using unbound references (I think). Here's the scenario. With JDBC's ResultSet you can get row values by index. I have a Bean instance I want to place selected values into. I'm looking for a way to avoid writing boiler plate mapping code but instead achieve something like:

static <T> void copy(Consumer<T> setter, Function<T, Integer> getter, Integer i);

And call it like:

copy(Bean::setAValue, ResultSet::getString, 0)

I don't want the bind Bean and ResultSet to instance too early since I want this to be usable with any bean of ResultSet.

The example I've been trying to work from is:

public static <T> void println(Function<T,String> function, T value) {
    System.out.println(function.apply(value));
}

Called via:

println(Object::toString, 0L);
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
nwillc
  • 103
  • 1
  • 6
  • 2
    And what is wrong with `bean.setAValue(rs.getString(0))`? How is your code superior to that one? Btw, what exactly is your problem? – Seelenvirtuose Aug 22 '16 at 16:51
  • You won't be able to use `Consumer` or `Function` - those interface declare methods that only accept a single argument. You need something that can accept two arguments (in the case of `Bean::setValue` - one representing `Bean`, then other representing `T`). – Oliver Charlesworth Aug 22 '16 at 16:53
  • It is not clear where you're having difficulty. You may run into issues with `ResultSet#getString` throwing a checked `SQLException`. I think that violates the `Function` interface. – bradimus Aug 22 '16 at 16:54
  • The `copy` method has to get the bean instance from somewhere. Further, a `Function` consumes a `T` and produces an `Integer`, that’s not even remotely matching a `ResultSet::getString`. But besides—what’s the question? You didn’t ask anything. – Holger Aug 23 '16 at 11:27

1 Answers1

3

When statically referencing instance methods, an extra parameter is added of the enclosing type. This parameter represents the instance on which to call the method.

For you that would mean, having to use a BiConsumer and BiFunction:

static <T> void copy(BiConsumer<Bean, T> setter,
    BiFunction<ResultSet, T, Integer> getter, Integer i);
Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93