在我下面提到的情况中,我在普通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.
更多推荐
发布评论