1

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.

5
  • 1
    It may make more sense to have it be a Runnable instead, since you're just running a void method, right? Commented Nov 20, 2015 at 18:07
  • @phflack It is more just a sample code here... It is more complex in my real code. Commented Nov 20, 2015 at 18:14
  • In that case, you should probably go with reflection if you dislike the elegancy of interfaces in OOP Commented Nov 20, 2015 at 18:17
  • @phflack It is just a little annoying because there is only one such object and I have to create a new interface just for it Commented Nov 20, 2015 at 18:19
  • Even with only being used once, just how many methods are in it? If there are a lot, it might make more sense to use a local class which you only ever use once, but is a bit more readable and maintainable. Commented Nov 20, 2015 at 18:23

2 Answers 2

5

By reflection:

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

But this is normally a very ugly thing to do.

Sign up to request clarification or add additional context in comments.

1 Comment

I did this o.getClass().getMethod("test").invoke(o);... works and a bit simpler
1

Alternatively...

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

1 Comment

It's an anonymous inner class, so Class.forName won't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.