Those things in the project---application of Java Reflection

Source: Internet
Author: User

Recent work has encountered a problem like this:

Do a test tool for all the interfaces in a project, using Java Swing technology, the project has different versions, not all versions of the interfaces are the same, and the tools I do need to be compatible with all versions.

So the question was introduced:

Some interfaces do not exist in the partial version, then the interface to perform this operation will be error, so in order to be compatible with all versions, it is necessary to consider the existence of the method before the method call, and in order not to throw an exception at compile time, when the method is called

It also needs to be called through reflection, as follows:

First, the use of reflection to determine whether the method exists

1 /**2 * Determine if the method exists3      *4      * @paramobj Jobjectservice instances5      * @paramMethodName Method Name6      * @paramParatypes method Parameter type array7      * @return8      */9      Public Static Booleanjudgemethodisexist (Object obj, String methodName, class[] paratypes) {Ten         Booleanresult =true; One         Try { A             if(NULL!=obj) { -Method method =Obj.getclass (). GetMethod (MethodName, paratypes); -             } the}Catch(Nosuchmethodexception ex) { - Showwarninfo (ex.tostring ()); -Log.error ("Exception occurred in:" + Mainjframe.hostname + "; details are:" +ex.getmessage ()); -result =false; +         } -         returnresult; +}

Parameter description:
(1) Obj: An object that invokes a method

(2) MethodName: The name of the method to invoke

(3) Paratypes: The type of parameter required by the method (multiple arrays)

By this method, you can determine whether the methodname (parameter type) method you call through the Obj object is present and will run Nosuchmethodexception exception if it does not exist.

Second, by reflection call method, avoid compile-time exception

1Sysuser =Mainjframe.getsysuser ();2Class[] Paramobj = {String.class,Long.class, String.class, String.class,int.class};
Determine if the method exists3 BooleanIsexist = Commonutil.judgemethodisexist (Sysuser, "Createbucket", paramobj);4 if(isexist) {5 Try{
Calling methods by Reflection6Class Clazz =Sysuser.getclass ();
Method name-The type of the parameter in the method (in order of parameter)7Method Createbucket = Clazz.getdeclaredmethod ("Createbucket", String.class,Long.class, String.class, String.class,int.class);8 intCreate = (int) Createbucket.invoke (Sysuser,bucketname, Long.parselong (bucketsize), Bucketloc, Bucketacl, Integer.parseInt ( Stringutil.emptytozero (bucketcycle));9 if(Create = = 1) {TenCommonutil.showinfo ("Bucket creation succeeded"); OneLog.info ("Bucket creation succeeded"); A}Else { -Commonutil.showwarninfo ("Bucket creation failed, server internal error! "); -Log.info ("Bucket creation failed, server internal error"); the } -}Catch(Exception ex) { - Commonutil.showwarninfo (Ex.getmessage ()); -Log.error ("Exception occurred in:" + Mainjframe.hostname + "; details are:" +ex.getmessage ()); + } -}

In the above code:
First line: The object that invokes the method Createbucket method Sysuser

Second line: An array of parameter types in the method, used when judging whether a method exists

Third line: Determine whether a method exists by using an array of objects, method names, and parameter types

With the above three lines, the method is present when the following task is performed, and the exception message is not present

Line six: Gets the class of the object

Line seventh: Gets the object's method object, and the parameter corresponds to the type of the method name and parameter

Line eighth: Call the Createbucket method by reflection on the method object, which is the Sysuser object and the required parameter (value), respectively

With these methods, a compile-time exception does not occur even if an interface in the object does not exist.

True, this is the first time in your project to encounter the Java reflection problem, it is necessary to record a bit!

Those things in the project---application of Java Reflection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.