Consider the following code:
public static void main(String[] args) {
File file = new File(\"C:\\\\someFile.txt\") {
public void doStuff() {
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".
It is possible to access that method. But I don't know why you would ever want to do this.
public static void main(String[] args) {
new File("C:\\someFile.txt") {
public void doStuff() {
// Do some stuff
}
}.doStuff();
}
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.
The nearest I have been able to get to your level of succinctness is:
public static void main(String[] args) {
abstract class FileThatDoesStuff extends File {
// Need a constructor that takes a String because File has one.
public FileThatDoesStuff(String filePath) {
super(filePath);
}
// It also does stuff.
public abstract void doStuff();
}
FileThatDoesStuff file = new FileThatDoesStuff("C:\\someFile.txt") {
@Override
public void doStuff() {
// Do some stuff
}
};
file.doStuff(); // "Can resolve method"
}
I have to admit I wish I could do:
abstract class DoesStuff<T> extends T {
public abstract void doStuff();
}