I wrote the following Java code and expected it to not compile but it did and also executed counterintuitively. I am using Java 17.
TestFunctionExecutor.java
@FunctionalInterface
public interface TestFunctionExecutor{
void execute();
}
TestClass.java
public class TestClass{
public static void main(String... args) {
TestClass test = new TestClass();
test.wrapper(test::sampleFunction);
}
public void sampleFunction() {
System.out.println("Inside sampleFunction");
}
public void wrapper(TestFunctionExecutor method) {
System.out.println("Before method execution");
method.execute();
System.out.println("After method execution");
}
}
Output -
Before method execution
Inside sampleFunction
After method execution
I thought since wrapper
expects an argument of type TestFunctionExecutor
and I am passing one of type TestClass
the compilation should fail. I used a debugger and looks like method
is a TestClass$$Lambda$1...
at runtime. This confuses me and I have a few questions -
- What is the type of
test::SampleFunction
? Is it notTestClass
or something likeTestClass$$sampleFunction...
? I am unable to deduce this with a debugger. - Why were there no errors here? Looks like the types somehow became compatible, how?
- How does
execute
know what code to execute? - Is this good code? My aim is to wrap a function so that some code runs before and after it.
Thanks!
Aucun commentaire:
Enregistrer un commentaire