我有一个名为MyFunctions
的clas定义了不同的函数func1
,func2
等。我还有一个类Process
,它存储分配给它的函数名。这个课程的对象:
Process p1 = new Process();
String fName1 = "func1";
p1.setFunctionName(fName1);
Process p2 = new Process();
String fName2 = "func2";
p2.setFunctionName(fName2);
为了运行正常的功能,我执行以下操作:
MyFunctions f = new MyFunctions();
if (p.getFunctionName() == "func1") {
output = f.func1(inputdata);
} else if (p.getFunctionName() == "func2") {
output = f.func2(inputdata);
}
我不确定这种方法是否有效。还有其他方法可以解决这个问题吗?
另一个问题:是否有可能在JAVA中做这样的事情?:
String fName = p.getFunctionName();
output = f."+fName+"(input);
答案 0 :(得分:2)
首先,这种方法并不完全正确。切勿使用==
来比较对象。请改用equals()
:
MyFunctions f = new MyFunctions();
if ("func1".equals(p.getFunctionName())) {
output = f.func1(inputdata);
} else if ("func2".equals(p.getFunctionName())) {
output = f.func2(inputdata);
}
其次,我建议你改用enum
。
public enum FunctionInvoker {
func1 {
public Object invoke(MyFunctions o, Object ... arg) {
o.func1(arg[0]);
}
},
func2 {
public Object invoke(MyFunctions o, Object ... arg) {
o.func2(arg[0], arg[1]);
}
},
}
现在用法如下:
String functionName = ...; // probably read from file, etc.
Object result = FunctionInvoker.valueOf(functionName).invoke(args);
答案 1 :(得分:1)
Java的Reflection API很可能对您有用。它允许您(除其他外)在运行时在类中查找方法(例如,当您在字符串中有方法名称时)并以这种方式调用方法。
一个简单的例子:
String inputdata = "Hello";
// Finds the method "func1" in class MyFunctions that takes a String argument
Method method = MyFunctions.class.getMethod("func1", String.class);
// Calls the method on a new MyFunctions object, passing in inputdata
// as the argument
Object result = method.invoke(new MyFunctions(), inputdata);
System.out.println("Return value: " + result);
答案 2 :(得分:1)
如果您有一组确定的函数,则使用public static
常量来声明函数的名称。
示例:
public static String FUNCTION1 = "func1";
public static String FUNCTION2 = "func2";
对于你的第二个问题,是的,可以使用java reflection。
答案 3 :(得分:1)
答案 4 :(得分:1)
我不确定这种方法是否有效。
MyFunctions f = new MyFunctions();
if (p.getFunctionName() == "func1") {
没有。 AFAIK它不会起作用。您正在比较String的引用,而不是比较它的内容。
if (p.getFunctionName() == "func1")
使用.equals
代替==
来比较2个字符串。
可以在JAVA中做这样的事情吗?
output = f."+fName+"(input);
您可以使用reflection in java做您想做的事。
答案 5 :(得分:1)
使用枚举来解耦:
public enum Function {
ONE {
public void call(Functions functions) {
functions.func1();
},
TWO {
...
};
public abstract void call(Functions functions); }
过程:
Process p1 = new Process(Function.ONE);
MyFunctions f = new MyFunctions();
p1.call(f);
希望你有这个想法:)