Java 8 method references : validation of methods at compile time

Viewed 2657

I'd like to use the new method references of Java 8 to provide more validation of some code at compile time.

Let's say I have a validateMethod method which requires one parameter : a "method" to be validated. For example :

validateMethod(foo, "methodA");

Here, the method would validate that foo#methodA() exists, at runtime.

Using method references, I'd like to be able to do :

validateMethod(foo::methodA);

So the existence of the method would be validated at compile time.

The problem is that it seems method references have to be assigned to a functional interface. For example, this :

Object dummy = foo::methodA;

Generates the error : "The target type of this expression must be a functional interface".

If I create a functional interface that has a compatible signature with the methodA method, it works :

@FunctionalInterface
public interface MyFunctionalInterface
{
    public String run();
}
MyFunctionalInterface dummy = foo::methodA;

Now the existence of foo#methodA() is validated at compile time, which is what I want!

But...

Let's say validateMethod doesn't know the signature of the method it has to validate. Is it still possible to implement it then?

Let's pretend we don't care about ambiguity and overloaded methods. Is it possible in Java 8 to implement some kind of method which would trigger the validation of any method reference?

For example :

public class Foo
{
    public String methodA()
    {
        return "methodA";
    }

    public String methodB(String str)
    {
        return "methodB";
    }

    public String methodC(String str, int nbr)
    {
        return "methodC";
    }
}

Foo foo = new Foo();
validateMethod(foo::methodA); // Compile
validateMethod(foo::methodB); // Compile
validateMethod(foo::methodC); // Compile
validateMethod(foo::methodD); // Error!

Would it be possible to implement validateMethod in such a way that any method reference would be accepted, so the existence of the method would be validated at compile time?

I tried :

public void validateMethod(Object obj){}

But it doesn't work : "The target type of this expression must be a functional interface"

This would work :

@FunctionalInterface
public interface MyFunctionalInterface
{
    public String run();
}
public void validateMethod(MyFunctionalInterface param){}

But only for methodA of the Foo class, because its signature (no parameter) is compatible with the functional interface's method signature!

Would it be possible to implement the functional interface MyFunctionalInterface in such a way that any method reference would be a valid parameter and therefore would be validated at compile time?

Any other ways you see to validate the existence of a method at compile time?

3 Answers
Related