I'm confused with method references. Consider the following script.
public class Main {
static interface I {
void m();
}
static class A implements I {
@Override
public void m() {
System.out.println("A");
}
}
static class B implements I {
@Override
public void m() {
System.out.println("B");
}
}
public static void main(String[] args) {
A a = new A(); B b = new B();
I i; Runnable r;
i = a;
r = i::m;
r.run(); // prints "A"
run(i); // also prints "A"
i = b;
r.run(); // prints "A" instead of "B"!
run(i); // now prints "B"
r = i::m;
r.run(); // prints "B"
run(i); // also prints "B"
}
public static void run(I i) {
Runnable r = i::m; // polymorphic reference
r.run();
}
}
So it seems that:
- The compiler cannot inline method references because they are polymorphic. They are not resolved at compilation time, but at runtime.
- But
i::m
does not behave likei.m()
...
So my question is:
Are method references using reflection? And why the hell only once?
Aucun commentaire:
Enregistrer un commentaire