Class Name for Java anonymous class [duplicate]

喜夏-厌秋 提交于 2019-12-13 05:22:48

问题


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;
}

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

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?


回答1:


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.

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) );



回答2:


No idea how you are running you code. Some points to note are as follows -

  • First if all where is the main() method? How does your program start? There must be one

public static void main(String args[])

method in your project.

  • Secondly see your method

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

Function signature dictates it should return an object of Class C(or it's subclass) but I see no such return statement. You must return c;

Finally the output of your code is Class Name: class nz.test.anon.B$1 in which B$1 means an anonymous class.



来源:https://stackoverflow.com/questions/18264422/class-name-for-java-anonymous-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!