如何在JAVA中使用反射从不同的类调用类的函数?

时间:2013-12-23 07:07:43

标签: java reflection

import org.apache.commons.beanutils.MethodUtils;
public class subscriber
{
    public calculator cal=new calculator();
    String funcName = "";
    int result;
    public void getValues(String strfuncName)
    {
            funcName= strfuncName; //has the function name of class calculator

    }

    public void giveResult()
    {
            result=cal.funcName();
     //i want it to call the function whose name is stored in funcName
    }
}

我如何使用反射和
来做到这一点 导入 org.apache.commons.beanutils.MethodUtils
并且由于函数调用可以是动态的,可以调用任何函数,我无法预定义它。

3 个答案:

答案 0 :(得分:1)

Method method = obj.getClass().getMethod("Methodname", new Class[] {});
String output = (String) method.invoke(obj, new Object[] {}); // String return type here, Sorry i mean yourType is your return type..

答案 1 :(得分:0)

来自我的blog

/**
 * If it exists, invoke methodName on receiver - passing
 * parameters (if they exist) as arguments. If
 * receiver.methodName(parameters) returns, return the
 * returned value.
 * 
 * @param receiver
 *          The receiver to invoke.
 * @param methodName
 *          The name of the method to call.
 * @param parameters
 *          The arguments to pass to the method.
 * @return The value returned from invoking methodName on
 *         receiver.
 * @throws Exception
 *           Any Exception thrown by invoking the method
 *           with the passed parameters.
 */
public static Object callMethod(Object receiver,
    String methodName, Object... parameters)
    throws Exception {
  if (receiver == null || methodName == null) {
    return null;
  }
  methodName = methodName.trim();
  if (methodName.length() == 0) {
    return null;
  }
  Class<?> cls = receiver.getClass();
  Method toInvoke = null;
  outer: for (Method method : cls.getMethods()) {
    if (!methodName.equals(method.getName())) {
      continue;
    }
    Class<?>[] mTypes = method.getParameterTypes();
    if (parameters == null && mTypes == null) {
      toInvoke = method;
      break;
    } else if (safeSize(mTypes) == 0
        || safeSize(parameters) == 0) {
      continue;
    } else if (safeSize(mTypes) != safeSize(parameters)) {
      continue;
    }

    for (int i = 0; i < mTypes.length; ++i) {
      if (!mTypes[i].isAssignableFrom(parameters[i]
          .getClass())) {
        continue outer;
      }
    }
    toInvoke = method;
    break;
  }
  if (toInvoke != null) {
    try {
      return toInvoke.invoke(receiver, parameters);
    } catch (Exception t) {
      throw t;
    }
  }
  return null;
}

/**
 * Returns the size (or length) of an array.
 * 
 * @param obj
 *          The Array to find the size of .
 * @return The length of the array (if object is an
 *         array), or 0.
 */
private static int safeSize(Object obj) {
  if (obj != null) {
    return Array.getLength(obj);
  }
  return 0;
}

答案 2 :(得分:0)

您可以提供以下内容:

 public class subscriber
    {
        public calculator cal=new calculator();
        java.lang.reflect.Method funcName;
        int result;
        public void getValues(java.lang.reflect.Method strfuncName)
        {
                funcName= strfuncName; //has the function name of class calculator

        }

        public void giveResult()
        {
                result= method.invoke(cal, arg1, arg2,...);

        }
    }

在某处您可以获取方法,并传递这样的方法:

     subscriber sub=new subscriber();
     java.lang.reflect.Method method;

        try {
          method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
          sub.getValues(method);
        } catch (SecurityException e) {
          // ...
        } catch (NoSuchMethodException e) {
          // ...
        }

参数标识了您需要的非常具体的方法(如果有多个重载可用,如果方法没有参数,则只给出methodName)。

了解Java Reflection