Nick Holt
Nick Holt

Reputation: 34311

Assign a reference to a `Function` using Reflection

With Java 8 it's now possible to get a reference to a method as a first class object using the :: syntax like this:

Map<Integer, String> strings = new HashMap<>();
...

Function<Integer, String> get = strings::get;
...

How do I achieve the same assignment using reflection (as opposed to coding it as shown)?

Upvotes: 2

Views: 58

Answers (2)

skiwi
skiwi

Reputation: 69269

You can do this by using (raw code warning):

Map<Integer, String> strings = new HashMap<>();
...

Method getMethod = strings.getClass().getMethod("get", Object.class);
Function<Integer, String> function = i -> getMethod.invoke(strings, i);

Your job now is to ensure that the parameter to get is an integer, and that it returns a specific type and to handle the exceptions, etc.

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533520

Using reflection will give you a method such as

Method get = Map.class.getMethod("get", Object.class);

however this doesn't bind to an object like you have in your example. What you can do is use MethodHandles. This can be bound to an object but I don't remember the exact syntax.

Upvotes: 1

Related Questions