|
|
Re: how to use the new defined methods in the Anonymous inner classes?
|
Posted: Jul 7, 2005 7:29 PM
|
|
Anonymous class is not intended to have extra methods defined to be used from outside. However, if you just want to use it for the heck of it, then you can do that. It is possible because every anonymous class is comiled into a class file. Once you compile the code, every anonymous class also gets a name which is of the form EnclosingClass$<<a number>>. The <<a number>> is assigned in document order as 1,2,3. So, in the following Test class Test$1 is the name of anonymous class. Its access is package level, so you can use it inside the same package as Test class. There are two ways to do that. 1. Create it directly like new Test$1(t) 2. Get its reference by calling t.m3() and then cast it to Test$1.
If you just have reference to an anonymous class then you can also use reflection (not included below) to call any method on that reference.
Once you compile Test.java, the anonymous class is compiled as following.
class Test$1 {
final Test this$0;
Test$1(Test test) {
this$0 = test;
super();
}
public void m1() {
System.out.println("Hello from anonymous class method.");
}
}
-----------------------------------
public class Test {
public Object m3() {
Object o = new Object() {
public void m1() {
System.out.println ( "Hello from anonymous class method.");
}
};
return o;
}
}
class AnonymousMethodTest {
public static void main(String[] args) {
Test$1 t1 = new Test$1 (t);
t1.m1();
// or you can write
// Test t = new Test();
// Test$1 t1 = (Test$1) t.m3();
// t1.m1();
}
}
|
|