Call different methods of this class (JAVA reflection) according to the parameters to reduce the judgment of if

Calling different methods of this class according to the parameters, there are about a dozen methods, if you use if to determine the code will be longer.

java code: 

public class Test{

    public static void main(String[] args) {
        Map<String, String> params = new HashMap<>();
        params.put("name", "小绵羊");
        String name="test1";//方法名 赋值不同调用不同方法
        try {
            Class<Test> test= Test.class;           
            Method methods=test.getMethod(name, Map.class);//Map是参数类型
            methods.invoke(new Test,params);//调用方法 返回object 可以进行强转

        }catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException                     
                e){
            e.printStackTrace();
        }
        
    }
    public Map<String, Object> test1( Map<String, Object> map) {
        System.out.println("我是test1"+map.get("name"));
        return map;
    }
    public Map<String, Object> test2( Map<String, Object> map) {
        System.out.println("我是test2"+map.get("name"));
        return map;
    }
    public Map<String, Object> test3( Map<String, Object> map) {
        System.out.println("我是test3"+map.get("name"));
        return map;
    }
        ....
}

operation result:

Guess you like

Origin blog.csdn.net/qq_36802726/article/details/112492934
Recommended