Can't call anonymous class method [duplicate]

2019-08-28 05:17发布

问题:

This question already has an answer here:

  • Using an arbitrarily defined method of an anonymous interface 4 answers

I can imagine some very creative code in Java:

Object thing = new Object() {
    public void speak() {
        System.out.println("Hi!");
    }
};
thing.speak();

Or even, to get the full closure effect, define a Function interface ... you get the idea?

Why doesn't this code work?

回答1:

i believe you can do it like this :-

new Object() {    
     public void speak() {
        System.out.println("Hi!");
     }
}.speak();

may help you .



回答2:

Not sure about the usefulness in this example, but some type of overriding method(s) on the original declaration is useful and because of it is overriding, you can call the methods. Otherwise in your case, just use the reflection as:

thing.getClass().getMethod("speak").invoke(thing);

and for the overriding method:

Object thing = new Object() {
   public void toString() {
      System.out.println("Hi! Me inside your mind!");
      return "not today!";
   }
};
thing.toString();