lundi 17 octobre 2016

Finding most specific overloaded method using MethodHandle

Suppose I have three methods in a given type:

public void foo(Integer integer);
public void foo(Number number);
public void foo(Object object);

Using a MethodHandle or reflection, I'd like to find the most specific overloaded method for an object of which the type is only known at runtime. i.e. I'd like to do JLS 15.12 at runtime.

For instance, suppose I have the following in a method of the above mentioned type that contains those 3 methods:

Object object = getLong(); // runtime type is Long

MethodHandles.lookup()
             .bind(this, "foo", methodType(Void.class, object.getClass()))
             .invoke(object);

Then I conceptually would want foo(Number number) to be chosen, but the above will throw an exception, since the API will only look for a foo(Long) method and nothing else.

Is there something in the MethodHandle API that automatically and at runtime does the same kind of resolution that the compiler does following JLS 15.12?





Aucun commentaire:

Enregistrer un commentaire