Java匿名类的类名

Java匿名类的类名

本文介绍了Java匿名类的类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Class A{

 public void test(){
   B b = new B();
   System.out.println( "Class Name: " + b.createClassC().getClass() );
 }

}

Class B{
   public C createClassC(){
     C c = new C(){
       @Override
       public boolean equals( Object other ){
         return true;
       }
     };
   }
}

Class C{
   int val = 8;
}

输出:类名称: package.name.here .B

Output:Class Name: package.name.here.B

有人可以告诉我为什么匿名类类型在getClass()方法中给出封闭类吗?这导致对象C上的.equals()始终失败.我的理解是,因为getClass给出了封闭的类名,所以永远不会调用覆盖的equals?

Can some one tell me why anonymous class types gives the enclosing class in the getClass() method? This causes the .equals() on the object C to fail all the time. My understanding is since the getClass gives the enclosing class name, the overridden equals is never invoked?

推荐答案

输出为Class Name: class nz.test.anon.B$1美元符号很重要. B $ 1表示B下的第一个匿名类.B$ 2是第二个,依此类推.

output is Class Name: class nz.test.anon.B$1 the dollar sign is important. B$1 means first anonymous class under B. B$2 is second and so on.

还调用了equals方法

also the equals method is being called

System.out.println( "This is true: " + b.createClassC().equals(b) );
System.out.println( "and so is this: " + b.createClassC().equals(this) );

这篇关于Java匿名类的类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:55