(written in the front: the seriously nonsense of a brick-and-tile worker who hasn't started)
Introduction: Recently done in the project, need to give the docking party to provide a public interface, according to the other side of the incoming XML file rootelement distribution call interface, the simplest use of if-else if mode, but it is too stupid to look at.
Scenario One: you need to distribute the interface according to the keyword
Disadvantages of using If-else mode:
- Look stupid.
- Not easy to read (personal view)
- Difficult to maintain
- Balabala ... Don't want to make up, just look at the unpleasant
If only one or two method is OK, if the method is more, the amount ... As below, self-experience.
1 Public classTestMethod {2 3 PublicObject Dispatchmethod (string name, string data) {4Object obj =NULL;5 6 if("MethodA". Equal (name)) {7obj =MethodA (data);8}Else if("MethodB". Equal (name)) {9obj =MethodB (data);Ten}Else if (...) { One ... A } - returnobj; - } the - PrivateObject MethodA (String data) { - ... - } + - PrivateObject MethodB (String data) { + ... A } at - ... -}
So I'm getting to the point, I'm using the reflection mode, matching the target method, I think can reduce maintenance and reading costs
Development environment: jdk1.8
Implementation code:
- Defines the target method enumeration, contains the rootelement information, invokes the method description, and the target method targetname
1 Public enumMethodenum {2 3METHODA ("METHODA", "Call Method A", "METHODA"),4METHODB ("METHODB", "Call Method B", "METHODB"),5 ;6 7 @Getter 8 PrivateString code;//rootelement9 Ten @Getter One PrivateString message; A - @Getter - PrivateString name;//Target Method Name the - Privatemethodenum (String code,string message,string name) { - This. Code =Code; - This. Message =message; + This. Name =name; - } + A Public StaticMethodenum Fromcode (String code) {//Filter The target method based on incoming code at for(Dockingfliggyhotelenum p:dockingfliggyhotelenum.values ()) { - if(P.code.equalsignorecase (code)) { - returnp; - } - } - return NULL; in } +}
- Defining the Reflection Method tool class
1 /**2 * Define Tool classes3 **/4 Public classMethodutil {5 6 Public StaticMethod Gettargetmethod (Class clazz, String methodName) {7Method[] methods = Clazz.getdeclaredmethods ();//get all methods, including private8 if(Methods! =NULL&& methods.length > 0) {9String regEx = "^" + methodName + "$";//get the method name that you want to find to match this regularTenPattern pattern =Pattern.compile (regEx); One for(Method method:methods) { AMatcher Matcher =Pattern.matcher (Method.getname ()); - Booleanrs =Matcher.find (); - if(RS) { the returnmethod; - } - } - } + return NULL; - } + A Public StaticObject Executetargrtmethod (Class clazz, String methodName, String xmlData) { atObject obj =NULL; - Try { -Method method =Gettargetmethod (Clazz, methodName); -obj =Method.invoke (Clazz, xmlData); -}Catch(Exception e) { - in } - returnobj; to } + -}
1 Public classTestdispatch {2 3 PublicObject Dispatch (string root, String xml) {4String name =Methodenum.fromcode (Root). Name;5Object obj = Executetargrtmethod ( This.getclass (), name, XML)6 returnobj;7 }8 9 PrivateObject MethodA (String xml) {TenObject obj =NULL; One ... A returnobj; - } - the PrivateObject MethodB (String xml) { -Object obj =NULL; - ... - returnobj; + } - + ... A}
The structure of the business code is clear, is not looking much more cool.
For a lot of similar scenarios, you can use the reflection mechanism.
Scenario Two: multiple places in the project need to insert data in large quantities, extract a public method, reduce the number of lines of code, why not?
By the way, this bulk insert method, the database using MySQL, project framework springboot,jdk1.8,5000 data inserted once, time consuming about 0.8s.
1 /**2 * @parambatchcount BULK Insert data volume at one time3 * @paramTarget object method keyword4 * @paramlist needs to insert a large amount of data5 * @throwsException6 */7 Public Static voidBatchinsert (Class Clazz,intBatchcount, String Target, list<?> List)throwsexception{8Method method =Gettargetmethod (target);9 intBatchlastindex = batchCount-1;//The last subscript of each batchTen for(intindex = 0; Index < List.size ()-1;){ One if(Batchlastindex > List.size ()-1){ ABatchlastindex = List.size ()-1; - if(Method! =NULL) { - Method.invoke (clazz,list.sublist (index, Batchlastindex)); the } - Break;//data is inserted, exit loop -}Else{ - if(Method! =NULL) { + Method.invoke (clazz,list.sublist (index, Batchlastindex)); - } +index = Batchlastindex + 1;//set the next batch subscript ABatchlastindex = index + (batchCount-1); at } - } -}
The experiment is over, the code analysis is written next time.
Written in the last
The code is pseudo-code, and maybe it's not written in any place.
For the above two scenarios, I can only think of this method at present ... If you have a better one, welcome to godless me.
Java Foundation----jdk1.8 Reflection Experiment