How to call functions in bulk with Java reflection

Call the function in a variable by reflection.

The class you want to call. Only four arithmetic operations are performed appropriately.

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.

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<>();
            //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

How to call functions in bulk with Java reflection
How to delete untagged images in bulk with Docker
How to learn JAVA in 7 days
How to use classes in Java?
How to name variables in Java
How to concatenate strings in java
How to call and use API in Java (Spring Boot)
Investigated how to call services with Watson SDK for Java
How to implement date calculation in Java
How to implement Kalman filter in Java
Multilingual Locale in Java How to use Locale
How to compile Java with VsCode & Ant
[Java] How to compare with equals method
How to do base conversion in Java
How to switch Java version with direnv in terminal on Mac
How to implement coding conventions in Java
How to embed Janus Graph in Java
How to get the date in java
How to call with One Touch (without confirmation) on Android (Java)
How to encrypt and decrypt with RSA public key in Java
[Personal memo] How to interact with a random number generator in Java
How to display a web page in Java
How to use Java framework with AWS Lambda! ??
How to get Class from Element in Java
How to use Java API with lambda expression
How to hide null fields in response in Java
[Java] How to substitute Model Mapper in Jackson
How to solve an Expression Problem in Java
How to write Java String # getBytes in Kotlin?
How to call AmazonSQSAsync
Azure functions in java
Contemplation: How to take advantage of functional interfaces in your own functions (java)
How to embed JavaScript variables in HTML with Thymeleaf
How to implement UICollectionView in Swift with code only
How to sort in ascending / descending order with SQLite
How to create a Java environment in just 3 seconds
[Java] How to omit the private constructor in Lombok
How to switch Tomcat context.xml with WTP in Eclipse
[Java] How to omit spring constructor injection with Lombok
How to deploy Java to AWS Lambda with Serverless Framework
How to input / output IBM mainframe files in Java?
How to use Z3 library in Scala with Eclipse
[Java] How to encrypt with AES encryption with standard library
How to create a data URI (base64) in Java
[Java] Refer to and set private variables with reflection
Organized how to interact with the JDK in stages
[How to insert a video in haml with Rails]
I dealt with Azure Functions not working in Java
How to mock a super method call in PowerMock
How to generate / verify ID token in Java Memo
How to use JDD library in Scala with Eclipse
How to convert A to a and a to A using AND and OR in Java
How to build Java development environment with VS Code
How to convert a file to a byte array in Java
How to Git manage Java EE projects in Eclipse
How to query Array in jsonb with Rails + postgres
Summary of how to implement default arguments in Java
How to put old Java (8 series) in macOS 10.15 Catalina
[Java] How to start a new line with StringBuilder
Notes on how to use regular expressions in Java
How to save a file with the specified extension under the directory specified in Java to the list