首页 > 解决方案 > 为什么 this.getClass 给它自己的类名而不是匿名类名?

问题描述

我通过在 public static void main() 方法中实现接口创建了匿名类。因此,java 8 对抽象方法 test() 的实现是由 C 类的 imple() 方法提供的。

所以,在 public static void main() 方法中,打印 _interface.getClass(),我得到了

package_path.Main$$Lambda$1/310656974 这绝对没问题。因为它打印的是匿名类名。

此外, _interface 指向堆中的匿名对象,因此我正在做 _interface.test();

所以, test() 方法现在的第一条语句是打印类名,

但最终它打印的是 package_path.C(告诉我 C 是类名)。这怎么可能?不应该再次打印 package_path.Main$$Lambda$1/310656974 吗?因为“this”在测试方法中意味着匿名,对吧?

@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();
    }
}

标签: javajava-8anonymous-classfunctional-interface

解决方案


希望这可以帮助您理解,当您声明

I _interface = new C()::imple;

你实际上实现的接口有点类似于(虽然不一样):

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

因此,当test调用该方法时,它首先创建一个实例,C该实例打印

class x.y.z.C 

作为班级。

因为“this”在测试方法中意味着匿名,对吧?

现在正如您在上面看到的,不再有从中imple 调用this的匿名类,因此不再代表匿名类。

正如 Holger 在评论中进一步澄清的那样,尽管在调用站点上表示为 lambda 或匿名类,但无论调用者的外观如何,this.getClass()类的内部方法都C将评估为。C.class

推荐:继续阅读并关注在 Java 中使用 lambda 表达式有什么运行时好处吗?


推荐阅读