Reputation: 15284
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
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
Reputation: 72854
By reflection:
o.getClass().getMethod("test", null).invoke(o, null);
But this is normally a very ugly thing to do.
Upvotes: 5