The class you want to call. Only four arithmetic operations are performed appropriately.
Calc.java
package refrectiontest;
public class Calc {
public int plus(int a, int b) {
return a + b;
}
public int minus(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
public int divide(int a, int b) {
return a / b;
}
}
Where to call.
RefrectionTest.java
package refrectiontest;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RefrectionTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
//Create an instance
Constructor<?> cons = Calc.class.getConstructor();
Calc calc = (Calc) cons.newInstance();
//Register the function name you want to use in the list
List<String> methodNames = new ArrayList<>();
methodNames.add("plus");
methodNames.add("minus");
methodNames.add("multiply");
methodNames.add("divide");
//Call functions collectively with the registered name.
//If the caller's signature is different, it is necessary to branch inside or separate the for statement.
for(String methodName : methodNames){
//Get a function pointer in a Method type variable.
//getMethod(Class instance created above,1st argument, 2nd argument, 3rd ...) of the function you want to use
//Method1 for as many signatures as you want to use,Define it as method2.
Method method = (Calc.class.getMethod(methodName,int.class,int.class));
//Use of functions. Since the return value of invoke is Object type, cast it according to the target function.
int result = (int)method.invoke(calc,20,10);
System.out.println(methodName + " = " + result );
}
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
Logger.getLogger(RefrectionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Output result plus = 30 minus = 10 multiply = 200 divide = 2
It may be useful when the method is specified as a String type. In this example, methodNames are added one by one by hand, The function names you want to call are method1, method2, method3, method4 ... If it is a serial number like
for(int i = 1;i<10;i++){
"method" + String.valuOf(i) ;
}
You may be able to measure the shortening of the code if it is automatically generated like this.
Recommended Posts