在Android应用程序中,如何根据用户说的内容执行不同的Java类。例如,用户单击按钮并说1.应用程序应执行名为1的Java代码。
答案 0 :(得分:0)
好吧,关于执行:
如果你有一个值为“One”的String(从任何地方)你可以查找一个具有相同名称的类并通过Reflection执行它的方法,或者如果确定了所有选项,你可以将对象映射到字符串,两种解决方案如下:
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");
}
地图解决方案如下:
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");
}