开发者

java anonymous inner class unreachable code

Java compiler complains when you write a code that is unreachable. For example

public void go()
{
    return;
    System.out.println("unreachable");
}

However, when you define a new method in an anonymous class which cannot be reached from anywhere, compiler does not complain. It allows you to do that, why? For example,

开发者_开发百科
class A
{
   public void go()
   {
     System.out.println("reachable - A");
   }
}
class B
{
   public static void main(String [] args)
   {
     A a = new A() {
              public void go()
              {
                System.out.println("reachable - B");
              }
              public void foo()
              {
                System.out.println("unreachable - B");
              }
           };
     a.go(); // valid
     a.foo(); // invalid, compiler error
  }
}


First of all: Eclipse does notify my that foo() is never used locally. It's a warning and not an error, however, for reasons pointed out by the other anserws.

Note that there is a way to reach foo():

new A() {
      public void go()
      {
        System.out.println("reachable - B");
      }
      public void foo()
      {
        System.out.println("unreachable - B");
      }
}.foo();

This works, because the type of the expression new A() {} is not A, but actually the anonymous subclass of A. And that subclass has a public foo method.

Since you can't have a variable with the same type, you can't access foo() this way from a variable.


That's only equivalent to allowing you to create private methods which aren't called anywhere in the class, really. It's not unreachable code in quite the same sense - and it could be accessed by reflection.

It's the kind of thing which might reasonably give a warning (particularly on IDEs which allow very fine-grained tweaking of warnings) but I don't think it should be an error.


In principle you could call the foo() method on a via reflection, so it is not always unreachable.

Try this after a.go();:

Method m = a.getClass().getDeclaredMethod("foo");
m.invoke(a);


public void go()
{
   foo();
   System.out.println("reachable - B");
}

public void foo()
{
   System.out.println("unreachable - B");
}

Simply another way to reach the foo method it to use it another method of the class. I should have understood this before asking. Sorry.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜