Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if JDK8 lambda can be assigned to type?

Edit: this question is malformed to the extent that I cannot really fix it, and is a bug somewhere in my project. The root cause of my problem is that myLambda.getClass() should not throw ClassNotFoundException, and the lambda works as expected.

Given the class of an interface

Class myIf = MyIf.class;

And a lambda instance

Object myLambda;

How can I determine if myLambda can be assigned to MyIf without throwing an exception ? This is a bit puzzling since myLambda.getClass() throws an exception. And the "obvious"

myIf.isInstance(myLambda) 

returns false

like image 693
krosenvold Avatar asked Mar 03 '14 07:03

krosenvold


1 Answers

Correct me again if my assumptions were incorrect, but you would do it as you normally would

static Class<?> clazz = MyIf.class;

public static void main(String[] args) throws Exception {
    method(() -> System.out.println("hello")); // lambda

}

public static void method(MyIf myIf) { 
    System.out.println(clazz.isAssignableFrom(myIf.getClass()));
}

static interface MyIf {
    public void execute();
}

prints

true

You don't actually ever get a reference to the lambda expression, the compiler generates a (synthetic?) class and an instance of it is passed to your method.

like image 80
Sotirios Delimanolis Avatar answered Oct 31 '22 06:10

Sotirios Delimanolis