Can't call anonymous class method [duplicate]

会有一股神秘感。 提交于 2019-12-25 07:47:44

问题


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();


来源:https://stackoverflow.com/questions/22049634/cant-call-anonymous-class-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!