English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Notes on the Application of Java Reflection in Actual Work

Recently, I encountered a problem like this:

To create a test tool for all interfaces in a project, using java Swing technology, the project has different versions, and not all interfaces are the same in all versions. My tool needs to be compatible with all versions.

This leads to the following problem:

If some interfaces do not exist in some versions, an error will be reported when executing this operation through the interface, so in order to be compatible with all versions, it is necessary to consider whether the method exists before the method call, and in order not to throw an exception at compile time, when calling the method

It also needs to be called through reflection, the specific implementation is as follows:

I. Use reflection to determine if a method exists

/**
   * Check if the method exists
   *
   * @param obj Instance of JObjectService
   * @param methodName Method name
   * @param paraTypes Array of method parameter types
   * @return
   */
  public static boolean judgeMethodIsExist(Object obj, String methodName, Class[] paraTypes) {
    boolean result = true;
    try {
      if (null != obj) {
        Method method = obj.getClass().getMethod(methodName, paraTypes);
      
    } catch (NoSuchMethodException ex) {
      showWarnInfo(ex.toString());
      log.error("Exception occurs at:") + MainJFrame.hostName + "; Detailed information is:" + ex.getMessage());
      result = false;
    
    return result;
  

Parameter introduction:

(1) obj: Represents the object to call a method on

(2) methodName: The name of the method to be called

(3) paraTypes: The parameter types required by the method (an array when there are multiple)

With this method, you can determine whether the method named methodName (parameter type is) called through the obj object exists. If it does not exist, a NoSuchMethodException will be thrown

Secondly, invoke the method by reflection to avoid compile-time exceptions

sysUser = MainJFrame.getSysUser();
    Class[] paramObj = {String.class, long.class, String.class, String.class, int.class};       //Check if the method exists
    boolean isExist = CommonUtil.judgeMethodIsExist(sysUser, "createBucket", paramObj);
    if (isExist) {
      try {            //Invoke method by reflection
        Class clazz = sysUser.getClass();            //Method name--Parameter types (in order)
        Method createBucket = clazz.getDeclaredMethod("createBucket", String.class, long.class, String.class, String.class, int.class);
        int create = (int) createBucket.invoke(sysUser, bucketName, Long.parseLong(bucketSize), bucketLoc, bucketAcl, Integer.parseInt(StringUtil.emptyToZero(bucketCycle)));
        if (create == 1) {
          CommonUtil.showInfo("Bucket creation successful");
          log.info("Bucket creation successful");
        } else {
          CommonUtil.showWarnInfo("Bucket creation failed, internal server error!");
          log.info("Bucket creation failed, internal server error");
        
      catch (Exception ex) {
        CommonUtil.showWarnInfo(ex.getMessage());
        log.error("Exception occurs at:") + MainJFrame.hostName + "; Detailed information is:" + ex.getMessage());
      
    

In the above code:

The first line: The object calling the createBucket method is sysUser

The second line: The parameter type array in the method is used when determining whether the method exists

The third line: Determine whether the method exists by object, method name, and parameter type array

By the above three lines, the task will be executed when the method exists, and an exception information will be prompted if it does not exist

The sixth line: Obtain the Class of the object

The seventh line: Obtain the Method object for the method, with parameters as the method name and the type of corresponding parameters

The eighth line: Reflectively call the createBucket method through the Method object, with parameters as the sysUser object and the required parameters (values).

By the above method, there will be no compilation-time exception even if some interface does not exist in the object.

To be honest, this is the first time I've encountered a problem with Java reflection in my own project, and it's necessary to record it!

Summary

That's all about the application notes of Java reflection in practice in this article. I hope it will be helpful to everyone. Those who are interested can continue to refer to this site:

Java Reflection Simple Tutorial

What You Need to Know About Java Reflection Mechanism

If there is anything insufficient, please leave a message to point it out. Thank you friends for your support to this site!

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting. Provide relevant evidence, and once verified, this site will immediately delete the infringing content.)

You May Also Like