Java 如何调用一个方法取决于另一个方法&x27;s参数?

Java 如何调用一个方法取决于另一个方法&x27;s参数?,java,Java,想象一下,我有一个方法在里面调用另一个方法。它可能如下所示: public void enclosingMethod(String parameter, boolean order){ MyType t = new MyType(); t.internalMethod(paramter, order); } public void internalMethod(String parameter, boolean order){ anotherMethod1(str1,

想象一下,我有一个方法在里面调用另一个方法。它可能如下所示:

public void enclosingMethod(String parameter, boolean order){
    MyType t = new MyType();
    t.internalMethod(paramter, order);
}

public void internalMethod(String parameter, boolean order){
    anotherMethod1(str1, order1);
    //etcetera
    anotherMethod31312(str31312, order31312);
}
其中
anotherMethodn,0
实现如下:

anotherMethodn(String parameter = "default", boolean order = true){
    //Implementation
}
enclosingMethod("PartnerStatistic", false);
问题是我需要调用一个anotherMethods,这取决于传递给
internalMethod(字符串参数,布尔顺序)
的参数。例如,我调用
enclosingMethod
方法如下:

anotherMethodn(String parameter = "default", boolean order = true){
    //Implementation
}
enclosingMethod("PartnerStatistic", false);
在这种情况下,我需要调用
anotherMethod23(“PartnerStatistic”,false)
,但另一个
anotherMethod
必须使用默认参数的值调用


我怎样才能比多次编写
if-else
子句更灵活呢?在Java中可能有一个合适的众所周知的设计模式,如果您不知道需要调用什么方法,可以使用反射来调用由其名称指定的方法

例如:

ClassName.class.getMethod("anotherMethod31312").invoke(instance, arg1, arg2);
您仍然必须以某种方式“计算”方法的名称,但可以避免以这种方式使用扩展的
if-else
结构。这种“计算”可以通过接收要调用的方法的名称来实现,例如,根据您的情况,也可以是简单的
String
串联,如
“anotherMethod”+i
,其中
i
是一个数字

Java也没有默认参数。要“模拟”默认参数,可以创建方法重载,该重载调用其他传递参数默认值的方法

模拟默认参数的示例:

public void doSomething(String someParam) {
}

public void doSomething() {
    doSomething("This is the default value for 'someParam'.");
}
使用它:

// Calling doSomething() with explicit parameter:
doSomething("My custom parameter");

// Calling doSomething() with default parameters:
doSomething();

Java有默认参数值吗?@talex当然没有。这就是我问这个问题的原因。这似乎是一个问题。你到底为什么想要31312种方法?你想实现什么?如果指导你调用哪些方法的规则是随机的,那么你就没有那么多选择了。但如果它们以某种方式受到约束,例如有固定数量的字符串可以用作
参数
,则简化是可能的。