Home > Back-end >  Invoke SET method in Java by given a String
Invoke SET method in Java by given a String

Time:11-14

I have a string variable which dependes on "i" variable, i want to call this string, like his method:

String nameSetClassifiedMethod= "setClassficationdesc"   i;

and i wanted something like this:

this.nameSetClassifiedMethod( some parametersIn);

I know this is not possible, because i can't invoke a method with a string like im doing, but i don't know any solutions for this.

I have some code that's whic is not mine, which is doing something like:

if (i == 0) {this.setClassficationdesc0(..)}
if (i == 1) {this.setClassficationdesc1(..)}
if (i == 2) {this.setClassficationdesc2(..)}

So i'm trying to invoke the method by string to reduce complexity

CodePudding user response:

Well you could call the method from a string variable using reflection. But instead, I suggest the following workflow:

String i = "One";

switch (i) {
    case "One":
        // call setClassficationdescOne(...)
        break;

    case "Two":
        // call setClassficationdescTwo(...)
        break;

    // ...
}

CodePudding user response:

It is possible. Please search and read the topic "Reflection in Java". In particular look at class Class and in it look at method getMethod. so you can do:

Method method = this.getClass().getMethod(...);

Once you get the method you can invoke it. (See Javadoc for class Method)

CodePudding user response:

In that case you would use reflection by doing something like the following:

String nameSetClassifiedMethod= "setClassficationdesc"   i;
Method method = Operations.class.getDeclaredMethod("nameSetClassifiedMethod", String.class); //here you should adapt it to your method's signature
method.setAccessible(true);
// and then
ClassWhichHoldsReflectedMethod instance = new ClassWhichHoldsReflectedMethod(); 
method.invoke(instance, params...);

Check this out for more.

CodePudding user response:

Maybe you're looking for Java 14 Switch Expressions:

int i = // initilizing the variable
    
switch (i) {
    case 0 -> this.setClassficationdesc0(..);
    case 1 -> this.setClassficationdesc1(..);
    case 2 -> this.setClassficationdesc2(..);
}
  •  Tags:  
  • java
  • Related