Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling newly defined method from anonymous class

Tags:

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

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

I am wondering if it is possible to call this method from outside somehow similar to:

date.someMethod(); 
like image 573
user1544745 Avatar asked Mar 20 '13 15:03

user1544745


People also ask

Can an anonymous class have multiple methods?

You can't. The only way to be able to call multiple methods is to assign the anonymous class instance to some variable.

Can anonymous class have static methods?

Anonymous classes also have the same restrictions as local classes with respect to their members: You cannot declare static initializers or member interfaces in an anonymous class. An anonymous class can have static members provided that they are constant variables.

Can anonymous class have abstract methods?

you can't and does not make sense to declare anonymous class as abstract class as anonymous are used as local class only once.


2 Answers

Good question. Answer is No. You cannot directly call date.someMethod();
Let's understand first what is this.

Date date = new Date()  { ... };  

Above is anonymous(have no name) sub-class which is extending Date class.

When you see the code like,

    Runnable r = new Runnable() {          public void run() {          }      }; 

It means you have defined anonymous(have no name) class which is implementing(not extending) Runnable interface.

So when you call date.someMethod() it won't be able to call because someMethod is not defined in superclass. In above case superclass is Date class. It follows simple overriding rules.

But still if you want to call someMethod then following is the step.

Fisrt way>
With reference variable 'date'
date.getClass().getMethod("someMethod").invoke(date);

Second way>
With newly created anonymous sub-class of Date class's object.

new Date()  {     public void someMethod() {           System.out.println("Hello");     } }.someMethod();   //this should be without reference 'date' 
like image 111
AmitG Avatar answered Sep 17 '22 15:09

AmitG


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.

like image 22
ppeterka Avatar answered Sep 16 '22 15:09

ppeterka