问题
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