-2

Interface:

interface A
{
   void run(String methName);
}

Classs:

class X implements A
{
    void run(String methName)
    {

    }
    void m1()
    {

    }
    void m2()
    {
    }
    void m3()
    {

    }

}

I want to invoke m1, m2 and m3 methods by name dynamically from run method without using reflection mechanism

Mahender Ambala
  • 363
  • 3
  • 18

2 Answers2

2

Don't overthink it:

switch (methName) {
  case "m1": m1(); break;
  case "m2": m2(); break;
  case "m3": m3(); break;
  default: throw new AssertionError();
}

If you want to do something a bit safer, you can define a strategy enum, something like:

enum Strategy {
  M1 { @Override public void run(X instance) { instance.m1(); } },
  M2 { @Override public void run(X instance) { instance.m2(); } },
  M3 { @Override public void run(X instance) { instance.m3(); } };

  public abstract void run(X instance);
}

then

 void run(Strategy strategy) {
   strategy.run(this);
 }

Now you can't pass in an arbitrary method name, but are limited to an instance of Strategy.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

As stated in this post,

Reflection is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.

So saying that you want to perform reflection without reflection makes no sense.

Community
  • 1
  • 1