0

I don't know how exactly to word this, but I will give it a shot.

I want to call a method based on a parameter. I'm not sure if this is possible but I surely hope it is because it would save about 200 lines of code and a hassle! Please let me know if I need to be more specific about anything!

public static void example(String a){
        System.(a).println("Hello")
   }

public static void main(String[] args){
        example("out");
    }

Thanks for your help!

OneCricketeer
  • 126,858
  • 14
  • 92
  • 185
Sammytron
  • 1
  • 1

3 Answers3

1

You can referenceSystem.out with "out" (or other possible fields) using Reflection but you'd ultimately end up adding more code for exception handling, not saving much.

OneCricketeer
  • 126,858
  • 14
  • 92
  • 185
-1

This is not possible, you will get the compile-time error below.

Cannot make a static reference to the non-static method example(String) from the type

Here (example) is in the non-static area & main method is static.

OneCricketeer
  • 126,858
  • 14
  • 92
  • 185
-1

try something like this

public void example(String a){
    Class<?> c = Class.forName("java.lang.system");
    Method method = c.getDeclaredMethod(a, parameterTypes);
    method.invoke(objectToInvokeOn, params);
   }

public static void main(String[] args){
        example("out");
    }
  • parameterTypes is of type Class[] and declares the parameters the method takes
  • params is of type Object[] and declares the parameters to be passed to the method
Ganesh Krishnan
  • 6,152
  • 2
  • 36
  • 47