java - 为什么 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();
}
}
解决方案
希望这可以帮助您理解,当您声明
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 表达式有什么运行时好处吗?
推荐阅读
- android - 如何在 Playstore 控制台中上传多个 APK
- python - 如何根据句子相似度对句子进行聚类和绘图?
- javascript - 你能把它作为参数传递给 React 中的无渲染组件吗?
- java - 在没有 Google Cloud SDK 的情况下向 Google Cloud 授权
- android - GestureListener.onFling kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull,参数 e1 - Android
- javascript - 将带有 JS 的 CSS 添加到每个数组元素
- wso2esb - 集群环境中的 carbon.xml 主机名
- java - 添加 Alt + F7 作为 Netbeans 平台中操作的快捷方式
- r - 由于方程和浮点数的重新排序导致输出不一致
- angular - 离子:检查设备是否有连接