getClass()在java中匿名接口的refrance上给出了类名(getClass() on refrance of an anonymous interface in java gives c

编程入门 行业动态 更新时间:2024-10-27 06:20:24
getClass()在java中匿名接口的refrance上给出了类名(getClass() on refrance of an anonymous interface in java gives class name)

在我下面提到的情况中,我在普通refrance上使用instanceof和getClass()时得到两个不同的o / p。 我有一个Interface Foo。

public interface Foo { void dispaly();}

给身体display(); 在另一个使用匿名块技术的类中。

public class ClassWithMainMethod { public static void main(String[] args) throws Exception{ Foo obj = new Foo(){ @Override public void dispaly() {System.out.println("msg");} }; System.out.println(obj instanceof Foo); // result: true System.out.println(obj.getClass());//result com.ClassWithMainMethod$1 obj.dispaly(); // result: msg }}

现在在obj.getClass ,为什么我没有得到com.Foo作为o / p。

In my below mentioned situation, I am getting two different o/p while using instanceof and getClass() on common refrance. I have a Interface Foo.

public interface Foo { void dispaly();}

giving body to display(); in side another class using anonymous block technique.

public class ClassWithMainMethod { public static void main(String[] args) throws Exception{ Foo obj = new Foo(){ @Override public void dispaly() {System.out.println("msg");} }; System.out.println(obj instanceof Foo); // result: true System.out.println(obj.getClass());//result com.ClassWithMainMethod$1 obj.dispaly(); // result: msg }}

Now at obj.getClass, why I am not getting com.Foo as an o/p.

最满意答案

这段代码

Foo obj = new Foo(){ @Override public void dispaly() {System.out.println("msg");} };

创建一个实现接口Foo的匿名类。 生成的匿名类与com.Foo ,并且没有它的名称。 在编译期间,匿名类被赋予名称,具体取决于它们的包含类。 格式为<containing class name>$<identifier> 。

你的包含类是ClassWithMainMethod ,你的类是里面的第一个匿名类,所以结果名是com.ClassWithMainMethod$1 。 由于此类实现了com.Foo ,因此instanceOf运算符返回true ,您可以调用display()方法。

This block of code

Foo obj = new Foo(){ @Override public void dispaly() {System.out.println("msg");} };

creates an anonymous class that implements the interface Foo. The resulting anonymous class is not identical to com.Foo and doesn't have it's name. During compilation, anonymous classes are given names, depending of their containing class. The format is <containing class name>$<identifier>.

Your containing class is ClassWithMainMethod and your class is the first anonymous class inside, so the resulting name is com.ClassWithMainMethod$1. Since this class implements com.Foo, the instanceOf operator returns true and you are able to invoke the display() method.

更多推荐

本文发布于:2023-07-07 15:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1065205.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:出了   接口   getClass   java   refrance

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!