Why does this.getClass give it's own class name rather than Anonymous class name?

Manikandan Kbk DIP :

I have created anonymous class by implementing interface I inside public static void main() method. So, by java 8 for the abstract method test(), the implementation is provided from imple() method of class C.

So, inside public static void main() method, printing _interface.getClass(), I got

package_path.Main$$Lambda$1/310656974 which is absolutely fine. Bacause it print's the anonymous class name.

Also, _interface is pointing to an anonymous object in heap and hence I'm doing _interface.test();

So, the first statement that test() method has now is to print the class name,

But eventually what it print was, package_path.C (telling me C is the class name). How is that possible? Shouldn't package_path.Main$$Lambda$1/310656974 be printed again? Because 'this' means anonymous inside the test method right?

@java.lang.FunctionalInterface
interface I {
    void test();
}

class C {
    void imple() {
        System.out.println(this.getClass());
        System.out.println("Inside Implementation");
    }
}

class Main {
    public static void main(String[] args) {
        I _interface = new C()::imple;
        System.out.println(_interface.getClass());
        _interface.test();
    }
}
Naman :

Hopefully, this might help you understand, that when you declare

I _interface = new C()::imple;

you've actually implemented the interface somewhat similar to (though not same as):

I _interface = new I() {
    @Override
    public void test() {
        new C().imple(); // creating an instance of class `C` and calling its 'imple' method
    }
};

Hence when the test method is called, it first creates an instance of C which prints

class x.y.z.C 

as the class.

Because 'this' means anonymous inside the test method right?

Now as you can see above, there is no more anonymous class from which imple is being called from, hence this is not representing the anonymous class anymore.

As Holger clarified in comments further, despite the representation as lambda or anonymous class at the calling site, the this.getClass() inside a method of class C will evaluate to C.class, regardless of how the caller looks like.

Recommend: Continue to read and follow on Is there any runtime benefit of using lambda expression in Java?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=68669&siteId=1