Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
171 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...