Call GetName method based on name

Source: Internet
Author: User

The problem is, I see a way to call the GetName () method based on name names.
The implementation of the method is then implemented using the judgment of the string
The code is as follows:

Public Object Getorderby () {
        if (order_title.equals (this.ordered)) {return
            getTitle ();
        } else if (Order_ Renderdate.equals (this.ordered)) {return
            getrenderdate ();
        } else if (Order_createdate.equals (this.ordered) ) {return
            getcreatedate ();
        } else if (order_lastmodified.equals (this.ordered)) {return
            getlastmodified ();
        } else {return
            getTitle ();
        }
    }

That way, if you add a Get method later, it means adding the Getorderby () method to the decision.
So I decided to use class reflection to transform this method, first defining a Dogetmethod method

Private Object Dogetmethod (String methodname) throws Exception {
        object result = null;
        object[] eo = new object[] {};
        String getmethodname = "Get" + methodname.tolowercase ();
        Method[] methods = GetClass (). GetMethods ();
        for (int i = 0; i < Methods.length i++) {method method
            = Methods[i];
            if (Getmethodname.equals (Method.getname (). toLowerCase ())) {Result
                = Method.invoke (this, EO);
            }
        return result;
    }

The getmethodname is synthesized from the MethodName group, then the method is found in method[], and then invoked with Invoke.
The argument to invoke this method is that the first argument is the class that specifies the containing method, and the second parameter is the parameter required by the specified method.
Finally modify the original Getorderby

Public Object Getorderby () {
        Object obj = GetTitle ();
        try {
            obj = Dogetmethod (getordered ());
        } catch (Exception e) {return
            obj;
        }
        return obj;
    }

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.