2013-04-25 142 views
2

嗨,我正在使用反射来实现某些功能。 我已经给出了类名,该类的方法名和需要传递给文件中该方法的参数值(取任何文件,不是约束)。 我必须用参数调用该方法。此方法不返回任何内容。 这个类有一个巨大的方法列表,每个方法的参数列表各不相同。并且我也有不同的排列和组合。 那么我怎么能做到这一点。 我曾尝试用不同的开关子句对硬件进行硬编码,但它是一个真正的开销和风险的事情来维护。 我们是否可以动态地做这件事,就像在飞行中从文件中读取方法名称及其参数并调用它。 任何小代码片段都会有所帮助。 TIA。如何将多个参数传递给java反射中的某个方法

+0

使用对象[] {PAR1,PAR2,..} – BlackJoker 2013-04-25 05:50:40

+1

记住,有StackOverflow的格式,你需要按输入_twice_。 – Zyerah 2013-04-25 05:50:50

+0

你可以分享方法参数的排列组合吗? – Apurv 2013-04-25 05:51:54

回答

6

大家好我找到了解决上述问题的方法。下面是示例代码片段。

package reflections; 

import java.lang.reflect.InvocationTargetException; 
import java.lang.reflect.Method; 

public class ReflectionTest { 
    public void method1(String str, int number) { 
     System.out.println(str + number); 
    } 

    public void method1(String str) { 
     System.out.println(str); 
    } 

    public void method1() { 
     System.out.println("helloworld"); 
    } 

    public static void main(String[] args) throws ClassNotFoundException, 
      InstantiationException, IllegalAccessException, 
      NoSuchMethodException, SecurityException, IllegalArgumentException, 
      InvocationTargetException { 
     // Step 1) Make an object array and store the parameters that you wish 
     // to pass it. 
     Object[] obj = {};// for method1() 
     // Object[] obj={"hello"}; for method1(String str) 
     // Object[] obj={"hello",1}; for method1(String str,int number) 
     // Step 2) Create a class array which will hold the signature of the 
     // method being called. 
     Class<?> params[] = new Class[obj.length]; 
     for (int i = 0; i < obj.length; i++) { 
      if (obj[i] instanceof Integer) { 
       params[i] = Integer.TYPE; 
      } else if (obj[i] instanceof String) { 
       params[i] = String.class; 
      } 
      // you can do additional checks for other data types if you want. 
     } 

     String methoName = "method1"; // methodname to be invoked 
     String className = "reflections.ReflectionTest";// Class name 
     Class<?> cls = Class.forName(className); 
     Object _instance = cls.newInstance(); 
     Method myMethod = cls.getDeclaredMethod(methoName, params); 
     myMethod.invoke(_instance, obj); 
    } 
} 

我希望这也能帮助别人。

+1

供参考:您通过在每行的前面添加四个空格来格式化代码;) – Tobber 2013-10-19 20:14:46

+0

@Bittenus我只是通过选择代码行来按Ctrl + K来格式化代码。这是代码格式警告提示,以格式化代码。反正从下次我会确定。谢谢 – 2013-10-20 14:24:10

+0

谢谢你,我对Java很有新意,我为此苦苦挣扎,只有一个问题。为什么你使用Integer.Type而不是.class? – 2016-01-13 20:00:49

2
public class ReflectionSample 
{ 
    private Object mString = null; 
    private int mValue; 

    public ReflectionSample() 
    { 
    } 

    public ReflectionSample(int oValue) 
    { 
     mValue = oValue; 
    } 

    public ReflectionSample(String oString) 
    { 
     mString = oString; 
    } 

    public ReflectionSample(String oString, int oValue) 
    { 
     setValues(oString, oValue); 
    } 

    public void setValues(String oString, int oValue) 
    { 
     mString = oString; 
     mValue = oValue; 
    } 

    public String toString() 
    { 
     return ""+mString+":"+mValue; 
    } 

    public void run() 
    { 
     String oInput = "Teststring"; 
     Class<?> cls; 
     String clsname = "main.ReflectionSample"; 
     Object rs = null; // ReflectionSample 
     Object rsc = null; 

     System.out.println(this.getClass().getName()); 
     try 
     { 
      System.out.println(clsname); 
      cls = Class.forName(clsname); 
      if(cls == null) 
      { 
       System.err.println(clsname + " doesn't exist"); 
       return; 
      } 

      // Look for a constructor which has a single string 
      Constructor<?> ct = null; 
      Class<?>[] param_types = new Class<?>[1]; 
      Object[] arguments = new Object[1]; 

      param_types[0] = String.class; 

      // get the string constructor 
      ct = cls.getConstructor(param_types); 

      // We only have one object 
      arguments = new Object[1]; 
      arguments[0] = oInput; 

      // Instantiate the object with passed in argument. 
      rs = ct.newInstance(arguments); 
      System.out.println("String constructor sample: "+rs); 

      // Instantiate with default constructor 
      param_types = new Class<?>[0]; 
      arguments = new Object[0]; 
      ct = cls.getConstructor(param_types); 
      rs = ct.newInstance(arguments); 
      rsc = rs; // Keep it for later, to lazy to call it again 
      System.out.println("Default constructor sample: "+rs); 

      // Instantiate with string and int constructor 
      param_types = new Class<?>[2]; 
      arguments = new Object[2]; 

      // Must be in the same order as the params I think 
      param_types[0] = String.class; 
      param_types[1] = Integer.TYPE;  // <-- Its a primitive so use TYPE not Class 

      arguments[0] = oInput; 
      arguments[1] = new Integer(1); 

      ct = cls.getConstructor(param_types); 
      rs = ct.newInstance(arguments); 
      System.out.println("String plus int constructor sample: "+rs); 

      // call the setValues method 
      param_types[0] = String.class; 
      param_types[1] = Integer.TYPE;  // <-- Its a primitive so use TYPE not Class 

      arguments[0] = oInput; 
      arguments[1] = 1; 

      System.out.println("setValues invocation before: "+rsc); 
      Method m = cls.getMethod("setValues", param_types); 
      m.invoke(rsc, arguments); 
      System.out.println("setValues invocation after: "+rsc); 

      // An alternative method to pass the parameters 
      m = cls.getMethod("setValues", String.class, Integer.TYPE); 
      m.invoke(rsc, oInput+"x", 2); 
      System.out.println("setValues invocation after: "+rsc); 
     } 
     catch(Throwable e) 
     { 
      System.err.println(e.getLocalizedMessage()); 
     } 
    } 
} 

输出:

main.ReflectionSample 
main.ReflectionSample 
String constructor sample: Teststring:0 
Default constructor sample: null:0 
String plus int constructor sample: Teststring:1 
setValues invocation before: null:0 
setValues invocation after: Teststring:1 

希望这有助于。

我不知道这是否是Java中的一个新特性,但我已经看到您现在可以使用参数调用,而不是使用数组,这可能会使您的代码更好地阅读(这是另一种方式)。如果您需要可变数量的参数,并且事先不知道会有多少个参数,那么分配数组的操作就会失败,并且应该也是向后兼容的。

相关问题