Recently, due to a module responsible for the project, there are many categories under this module, and each category has an encoded code, and this value is carried as a parameter. But each code does correspond to a method.
There are many code values, and I don’t want to make ifelse or switch judgments, so I searched for information, which mainly made me find that using Java’s reflection mechanism can perfectly solve this problem
The test code is as follows: (can carry multiple parameters)
package com.escs.xmlutils;import java.lang.reflect.Method;public class Test {public String ceshi(){System.out.println("1111111111111");return "success";} public static void main(String[] args) throws Exception { //Write your own class name and path in it Class<?> c = Class.forName("com.escs.xmlutils.Test");Object obj = c.newInstance();//The first parameter is written as the method name, the second/third/...it is written as the type of the parameter in the method parameter list Method method=c.getMethod("ceshi2", String.class,int.class);//invoke executes the method and carries the parameter value String str2= (String) method.invoke(obj, new Object[]{"myname",4}); System.out.println(str2); } public String ceshi(String str){ //for(int j=0;j<Integer.valueOf(i);j++){ System.out.println(str); //} return str; } public String ceshi2(String str,int i){ for(int j=0;j<i;j++){ System.out.println(str+"22222"); } return str; } } This will make it easier if the method name is dynamically spliced. For example, my code values have 100, 1~100, and my code methods are ReturnCodeList(); at this time, we extract the above method and return the value we need, for example:
public String fanShe(String methodName,String className) throws ClassNotFoundException, SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{//Write your own class name and path in it Class<?> c = Class.forName(className);Object obj = c.newInstance();//The first parameter is the method name, the second/third/...Write the type of the parameter in the method parameter list Method method=c.getMethod(methodName, String.class,int.class);//invoke executes this method and carries the parameter value String str2= (String) method.invoke(obj, new Object[]{"myname",4});return str2; }Of course, in actual needs, you still need to draw the methods yourself according to the needs of the project. I hope it will be helpful to everyone.
The above example of the dynamic execution method of Java reflection splicing method name is the entire content shared by the editor. I hope it can give you a reference and I hope you can support Wulin.com more.