简体   繁体   中英

If I have a method name stored in a 2D array as a String, is it possible for me use that String to call said method?

I am trying to write a program that will help me calculate conversions of certain cooking measurements. I'm sure there are easier ways to go about this, but this is what I've got so far:

public void sort(String[] s)
{
    for (int i = 0; i < s.length; i++)
        s[i] = s[i].toLowerCase();

    try
    {
        if (s[0].equals("metric"))
        {
            for (int i = 0; i < metric.length; i++)
            {
                if (s[1].equals(metric[i]))
                {
                    metric[i][1]();
                }
            }

        } else if (s[0].equals("imperial"))
        {

        }
    } catch (IllegalArgumentException e)
    {
        System.out.println(e);
        System.out.print(errorMessage);
    }
}

s is an array containing information about what the user is converting from, to, and how much. I have also made two 2D arrays containing in each 1st-dimension element the measurement, and the corresponding method name that goes with it. What I want to do is extract that method name from the 2d array, thus calling the method. For example, the line that says metric[i]1; should call what ever method name is stored at metric[i][1]. How would I go about this if at all possible? Also sorry if this question is confusing, and if you have input on how this could be program could be written more intuitively, I would appreciate it.

Yeah, if you know, and can access the class...

Here is an example of how to run a method by name (Let selectedClass be the class in which its located):

Method theMethod = selectedClass.getClass().getMethod("methodName", null);
theMethod.invoke(selectedClass, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM