In an android app, how to execute different Java classes based on what the user says. For example, the user clicks on a button and says 1. The app should execute the Java code with name 1.
Asked
Active
Viewed 71 times
0

Phantômaxx
- 37,901
- 21
- 84
- 115

Yash Desai
- 50
- 8
-
Your questions is about the recognition or the execution? – Marcos Vasconcelos Nov 06 '17 at 13:52
-
Its about what API to use to convert voice to text and then how to execute a specific Java class. – Yash Desai Nov 06 '17 at 14:35
-
Those are two questions, I can answer the second one. – Marcos Vasconcelos Nov 06 '17 at 14:47
-
Ah okay, waiting for your answer about the execution – Yash Desai Nov 06 '17 at 14:49
1 Answers
0
Well, about the execution:
If you have a String with the value "One" (from anywhere) you can lookup a class with the same name and execute the methods from it trough Reflection, or if all options are determined you can map objects to the strings, both solutions are as follow:
package classes;
public class One {
public void doThings() {}
public void doThings(String xx) {}
}
public static void main(String[] args){
String className = "One"; //Imagine that it come from Voice-To-Text
Class<?> clazz = Class.getDeclaredClass("classes." + className);
Method doThings = clazz.getDeclaredMethod("doThings");
Method doThingsWithArgs = clazz.getDeclaredMethod("doThings", String.class);
Object instance = clazz.newInstance();
doThings.invoke(instance);
doThingsWithArgs.invoke(instance, "String as argument");
}
You can also share a interface for all implementers such:
public interface DoThings {
void doThings() {}
void doThings(String xx) {}
}
package classes;
public class One implements DoThings {
public void doThings() {}
public void doThings(String xx) {}
}
public static void main(String[] args){
String className = "One"; //Imagine that it come from Voice-To-Text
Class<?> clazz = Class.getDeclaredClass("classes." + className);
DoThings instance = (DoThings) clazz.newInstance();
instance.doThings();
instance.doThings("String as argument");
}
The Map solution is as follow:
public static void main(String[] args){
Map<String, DoThings> calls = new HashMap<String, DoThings>();
calls.add("One", new One());
calls.add("Second", new One());
String className = "One"; //Imagine that it come from Voice-To-Text
DoThings instance = (DoThings) calls.get(className);
instance.doThings();
instance.doThings("String as argument");
}

Marcos Vasconcelos
- 18,136
- 30
- 106
- 167
-
Looking back, This seems like such a stupid question from my side :see-no-evil: – Yash Desai Dec 14 '18 at 19:22