SwiftMango
SwiftMango

Reputation: 15284

How to call a singleton method?

I have a singleton object like:

Object o = new Object () {
  public void test() {
    //...
  }
};

But I cannot use o.test() because the class/interface does not have that method. Is there any way to achieve this using meta programming such as getMethods? Please do not suggest declaring an interface.

Upvotes: 1

Views: 51

Answers (2)

Michael Queue
Michael Queue

Reputation: 1400

Alternatively...

Class cls = Class.forName(className);
Method method = cls.getMethod("test", new Class[0]);
Object o = method.invoke(null, new Object[0]);

Upvotes: 1

M A
M A

Reputation: 72854

By reflection:

o.getClass().getMethod("test", null).invoke(o, null);

But this is normally a very ugly thing to do.

Upvotes: 5

Related Questions