deepesh kumar deepesh kumar - 2 years ago 122
Java Question

getClass() on refrance of an anonymous interface in java gives class name

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
in side another class using anonymous block technique.

public class ClassWithMainMethod {
public static void main(String[] args) throws Exception{
Foo obj = new Foo(){
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
, why I am not getting com.Foo as an o/p.

Answer Source

This block of code

 Foo obj = new Foo(){
     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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download