I found a collection of tasks and solves it in java for the sake of interest. Faced a problem.

switch (input) { case 1: System.out.print(ts.task_1()); break; case 2: ts.task_2(); break; case 3: ts.task_3(); break; case 4: ts.task_4(); break; //и так далее до 1000 

Is it possible to somehow change the approach to the implementation of the class to call tasks in large quantities?

  • four
    HashMap<Int, Runnable> - rjhdby

1 answer 1

You can use reflection:

  TS ts; Class clazz=ts.getClass(); if(input==1) System.out.print(ts.task_1()); else { //получаем ссылку на метод с именем task_*() Method method=clazz.getDeclaredMethod("task_"+input, null); if(method!=null) //вызываем метод method.invoke(ts, null); } 
  • And what about 1 ? - rjhdby
  • see response update - Barmaley
  • hm ... And what to do with 237 , where there will be, for example, finalCountdown.start(10); ? - rjhdby
  • and what to do if in 12980 call fuck_em_all() ? - Barmaley
  • Think about where the call operator appeared in Java: D - rjhdby