根据用户音频输入执行代码

Execute code based on user audio input

在 android 应用程序中,如何根据用户所说的执行不同的 Java 类。例如,用户单击按钮并说 1。应用程序应执行名称为 1 的 Java 代码。

嗯,关于执行:

如果您有一个值为 "One" 的字符串(来自任何地方),您可以查找具有相同名称的 class 并通过反射从中执行方法,或者如果确定了所有选项您可以将对象映射到字符串,两种解决方案如下:

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");
}

您还可以为所有实施者共享一个界面,例如:

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");
}

Map解决方案如下:

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");
}