Calling newly defined method from anonymous class

前端 未结 6 1887
南笙
南笙 2020-12-01 16:26

I instantiated an object of an anonymous class to which I added a new method.

Date date = new Date() {
    public void someMethod() {}
}

I

6条回答
  •  一生所求
    2020-12-01 16:41

    Basically no.

    This uglyness can do it however...

    Date date = new Date() {
      public Date someMethod() { 
         //do some stuff here
         return this;
      }
    }.someMethod();
    

    But aside from this, you will only be able to call that method (which does not exist in the parent class) using reflection only, like this:

    date.getClass().getMethod("someMethod").invoke(date);
    

    (try-catch left out for sake of clarity...)

    But seriously, don't do this! I'd feel being hated by the person who wrote this code, if I stumbled upon this in a codebase I have to work on.

提交回复
热议问题