Invoking a method of an anonymous class

前端 未结 4 550
-上瘾入骨i
-上瘾入骨i 2020-12-09 07:27

I learned the other day that you can do this

new Object() {
    void hello() {
        System.out.println(\"Hello World!\");
    }
}.hello();
4条回答
  •  攒了一身酷
    2020-12-09 08:23

    Adding to Sotirios' answer, here's how to invoke the method through reflection:

    Object o = new Object() {
        void hello() {
            System.out.println("Hello World!");
        }
    };
    
    Method hello = o.getClass().getDeclaredMethod("hello");
    hello.invoke(o);
    

    This allows you to call the method more than once, but other than that, makes little sense.

提交回复
热议问题