How do I invoke a Java method when given the method name as a string?

前端 未结 21 2077
耶瑟儿~
耶瑟儿~ 2020-11-21 04:50

If I have two variables:

Object obj;
String methodName = \"getName\";

Without knowing the class of obj, how can I call the met

21条回答
  •  不知归路
    2020-11-21 05:29

    This sounds like something that is doable with the Java Reflection package.

    http://java.sun.com/developer/technicalArticles/ALT/Reflection/index.html

    Particularly under Invoking Methods by Name:

    import java.lang.reflect.*;

    public class method2 {
      public int add(int a, int b)
      {
         return a + b;
      }
    
      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("method2");
           Class partypes[] = new Class[2];
            partypes[0] = Integer.TYPE;
            partypes[1] = Integer.TYPE;
            Method meth = cls.getMethod(
              "add", partypes);
            method2 methobj = new method2();
            Object arglist[] = new Object[2];
            arglist[0] = new Integer(37);
            arglist[1] = new Integer(47);
            Object retobj 
              = meth.invoke(methobj, arglist);
            Integer retval = (Integer)retobj;
            System.out.println(retval.intValue());
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
    }
    

提交回复
热议问题