0

is their a way to return a method if the user inputs a method into the console? Currently i have a problem where i need the user to type the method name and then have the method occur, however due to how comeplex the methods are, it would have to be a massive if statement or mutliple arraylists to bring the answer back if there isnt an a way. Is there a way for the a system.in command to return not as a string or int, but in a way that the computer will read it as a normal call to a method?

WolVes
  • 1,286
  • 2
  • 19
  • 39
  • 1
    There's the giant OOP way which is going to probably involve extending `Callable` and having a big `HashMap` (or factory) of them, etc ... and then there's reflection. Pick one :) – Brian Roach Jan 21 '14 at 05:48

1 Answers1

1

You can call method by name using reflection. As simple solution you can call method via reflection on every user request. As improvement, you can use reflection to build some kind of registry of methods at startup.

Community
  • 1
  • 1
Sergey Passichenko
  • 6,920
  • 1
  • 28
  • 29
  • Yes he can - but it's bad practice! – Nir Alfasi Jan 21 '14 at 05:24
  • @alfasin so do you have a better idea? – Scary Wombat Jan 21 '14 at 05:25
  • It's bad practice, if it's used everywhere. But in some simple cases it may be good solution. – Sergey Passichenko Jan 21 '14 at 05:26
  • Yes, the OO way: activate a selector method of the object with the string (user input) and have the selector choose the correct method and activate it. I understand that he's got a "massive if statement" but that may be due to a bad design. Need to see all the details in order to comment to that. – Nir Alfasi Jan 21 '14 at 05:28
  • From Effective Java, Item53: Prefer interfaces to reflection "...As a rule, objects should not be accessed reflectively in normal applications at runtime." There are 3 good reasons why NOT to use reflection - I recommend on reading the book or at least this section before the next time you choose to use reflection :) – Nir Alfasi Jan 21 '14 at 05:31
  • i appreciate what you are saying alfasin and i agree with you. But in this particular situation im having a hard time finding a way around it including rewriting the code, – WolVes Jan 21 '14 at 05:36