St.Antario
St.Antario

Reputation: 27375

How to invoke a method depends on the another method's parameter?

Imagine that I've a method which invoke another method inside. It may look like the following:

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

Where anotherMethodn, 0 < n < 31312 implements as follows:

anotherMethodn(String parameter = "default", boolean order = true){
    //Implementation
}

The thing is I need to invoke one of anotherMethods depends on the parameter passed to the internalMethod(String parameter, boolean order). For instance, I invoke enclosingMethod method as follows:

enclosingMethod("PartnerStatistic", false);

In this case I need to invoke anotherMethod23("PartnerStatistic", false), but another anotherMethods must be invoked with default argument's value.

How can I do it more flexible rather than to writeif-else clause many times ? May be there is a suitable well-know design pattern for?

Upvotes: 0

Views: 601

Answers (1)

icza
icza

Reputation: 417562

In Java if you don't know what method you'll need to invoke, you can use reflection to invoke the method specified by its name.

Example:

ClassName.class.getMethod("anotherMethod31312").invoke(instance, arg1, arg2);

You still have to "calculate" the name of the method somehow, but you can avoid using extensive if-else structures this way. This "calculation" can be by receiving the name of the method to call for example, or depending on your case can be simple String concatenation like "anotherMethod" + i where i is a number.

Also Java has no default parameters. To "simulate" default parameters, you can create an overload of the method which calls the other passing default values for the parameters.

Example to simulate default parameters:

public void doSomething(String someParam) {
}

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

And using it:

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

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

Upvotes: 1

Related Questions