Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

java - Calling newly defined method from anonymous class

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();
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...