Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an arbitrarily defined method of an anonymous interface

Tags:

Consider the following code:

public static void main(String[] args) {     File file = new File("C:\\someFile.txt") {         public void doStuff() {             // Do some stuff         }        };      file.doStuff(); // "Cannot resolve method" } 

When we try to call our newly defined method doStuff(), it isn't possible. The reason for this is that file is declared as an object of type File and not as an instance of our new, anonymous child class.

So, my question is, is there any 'nice' way to achieve this behaviour? Other than the obvious (which is to just, declare the class properly).

like image 458
Xenoprimate Avatar asked Sep 06 '13 10:09

Xenoprimate


2 Answers

That's not possible, because you are trying to call the method subclass on super class reference. And that method is not defined in super class itself. The anonymous class is just a subclass of File there.

However, a workaround is to go through reflection:

file.getClass().getMethod("doStuff").invoke(file); 

The getClass() method will return the runtime type of file, and then you can get the method for that class using Class#getMethod() method.

Well, I'm not a big fan of reflection myself. A better way would of course be to create a class by extending the super class, if you are going to do these kinds of stuff. It would be really a pain in the head, working your way out using reflection, for what can be easily done using a simple modification.

like image 127
Rohit Jain Avatar answered Sep 24 '22 08:09

Rohit Jain


The nice way is not to use anonymous inner class in your case but define your own class that extends File and add any methods you need there.

class StuffedFile extends File {     // implement all needed constructors     public void doStuff() { /*.....*/} } 

Now you can use it as following:

MyFile f = new MyFile("..."); f.doStuff(); 

However whole this attempt to extend File does not sound as a good design. Create other class that can accept file and do stuff on it. You will achieve better encapsulation and code reusability.

EDIT Obviously you can use reflection to call any method you want but I cannot call this "nice solution". I can call this "possible workaround".

like image 32
AlexR Avatar answered Sep 25 '22 08:09

AlexR