Is it possible to postpone function call binds to runtime in Java?
-
06-07-2021 - |
Question
Consider a simple case where I ask a user to select a fruit among 10 different fruits. Say the fruits are, apples, oranges, mangoes,... etc., If the user selects apples, I call apples(), if he selects mangoes, I call mangoes() and so on...
To select which function is to be called, I DON'T want to use a switch or if-else statements. How do I select which function is to be called during run-time?
NOTE : The programming language I am using is Java
Solution
Use java Refection api to call function at runtime.
Class noparams[] = {};
Class cls = Class.forName("com.test.Fruit");
Object obj = cls.newInstance();
//call the printIt method
Method method = cls.getDeclaredMethod("apples", noparams);
method.invoke(obj, null);
OTHER TIPS
Use Reflection
.
eg:
Write all the functions in a class ; say com.sample.FruitStall
Then use below code.
String className = "com.sample.FruitStall";
String methodName = "apple"; //here you will choose desired method
Object result;
Class<?> _class;
try {
_class = Class.forName(className);
} catch (Exception e) {
e.printStackTrace();
}
Object[] args = new Object[1]; // To Supply arguments to function
result = _class.invokeMethod(methodName, args);
use the design pattern "Command". http://www.codeproject.com/Articles/186192/Command-Design-Pattern
hiding the details of the action it needs to perform.