Recently because of a module responsible for the project, there are many classifications under the module, each of which has a coded code, which is carried over as a parameter. But each code does correspond to one method.
Code value There are many, they do not want to do ifelse or switch judgments and then crazy search data, mainly let me find the use of Java reflection mechanism can be a perfect solution to this problem
The test code is as follows: (can carry multiple parameters OH)
Package com.escs.xmlutils;
Import Java.lang.reflect.Method;
public class Test {public String Ceshi () {System.out.println ("1111111111111");
Return "Success"; The public static void main (string[] args) throws Exception {//Inside writes its own class name and path class<?> C = class.forname ("com".
Escs.xmlutils.Test ");
Object obj = c.newinstance (); The first parameter writes the method name, the second \ Third \ ...
The type of the parameter in the method parameter list is written Method=c.getmethod ("Ceshi2", String.class,int.class);
Invoke is to execute the method and carry 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; }
}
So if the dynamic splicing method name is simpler. For example, my code value has 100, respectively, 1~100, My Code method is Returncodelist (); At this point, 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{
//Inside Write own class name and path
class<?> c = class.forname (className);
Object obj = c.newinstance ();
The first parameter writes the method name, the second \ Third \ ... The type of the parameter in the method parameter list is written
Method=c.getmethod (methodname, string.class,int.class);
Invoke is to execute the method and carry the parameter value
string str2= (String) method.invoke (obj, new object[]{"MyName", 4});
return str2;
}
Of course, in the actual demand or according to the needs of the project to extract their own methods. I hope it will help you.