简体   繁体   English

Java-反射。 在setter方法中动态创建的多参数类对象中设置Value

[英]Java - Reflection. Set Value in the setter method multiple argument class object which are dynamically created

I have a Bean class User I create object dynamically during run time.I can do set the value in setter method but that setter method have multiple arguments. 我有一个Bean类用户,我在运行时动态创建对象。我可以在setter方法中设置值,但该setter方法有多个参数。

This My User Bean Class 我的用户Bean类

 public class User {

     private String name1;
     private String name2;
     private String name3;
     private int age1;
     private int age2;


     public String getName1() {
        return name1;
    }
    public void setName1(String name1,String name2,String name3) {
        this.name1 = name1;
        this.name2 = name2;
        this.name3 = name3;
    }

    public int getAge1() {
        return age1;
    }
    public void setAge1(int age1,int age2) {
        this.age1 = age1;
        this.age2 = age2;
    }

    @Override
    public String toString() {
        return "StudentUser [name1=" + name1 + ", name2=" + name2 + ", name3=" + name3 + ", age1=" + age1 + ", age2="
                + age2 + "]";
    }

I want to invoke this setter method using reflection.I can find anything during runtime like method Name method Parameter Type and also have order of Parameter Type. 我想使用反射调用此setter方法。在运行时可以找到任何东西,例如方法Name方法的Parameter Type,并且具有Parameter Type的顺序。

for my case I have some set of default values for setter method like primitive type and non primitive type and find the method arguments type during run time and invoke setter method and set default values for them 就我而言,我有一些setter方法的默认值,例如原始类型和非原始类型,并在运行时找到方法参数类型,并调用setter方法并为其设置默认值

My Main Method :- 我的主要方法:

public static Object getBean(String beanClassName) throws Exception
    {
        Class klass = Class.forName(beanClassName);   //->Get Class Name By Path
        Object obj = klass.newInstance();             //->Create The Object of Class 
        Method[] b = klass.getDeclaredMethods();      //->Get Declared Method in Class

        for(Method m : b)
        {   
           Type[] pType = m.getGenericParameterTypes();

            for(int i=0;i<pType.length; i++)
            {

                 System.out.println("The Arguments :"+pType[i]+" Arguments Order :"+i);
                   if(pType[i].equals(String.class))
                   {
                        m.setAccessible(true);
                        m.invoke(obj,"Hello");
                   }
                   else if(pType[i].equals(int.class))
                   {

                       System.out.println("Machted int");
                       m.setAccessible(true);
                       m.invoke(obj,21);
                   }

            }
        }

        return obj;
    }

I can do that i have execpetion ArgumentMissMacth.I want to set Every String Type to "Hello" and every Int Type to 23 And Object To Null How can identify dynamically which order to set. 我可以通过执行ArgumentMissMacth.I来实现。我想将每个字符串类型设置为“ Hello”,将每个Int类型设置为23,将对象设置为空。如何动态识别设置的顺序。

My case I would know Method Parameter type but have to set the deafult value according to method parameter type. 我的情况我会知道方法参数类型,但必须根据方法参数类型设置默认值。

Method takes 3 argument but you call method with only 1 argument. 方法有3个参数,但是您仅用1个参数调用方法。 You should collect all parameters value then invoke method. 您应该收集所有参数值,然后调用方法。

Here is sample code. 这是示例代码。

public static Object getBean(String beanClassName) throws Exception {
    Class klass = Class.forName(beanClassName); // ->Get Class Name By Path
    Object obj = klass.newInstance(); // ->Create The Object of Class
    Method[] b = klass.getDeclaredMethods(); // ->Get Declared Method in
                                                // Class

    for (Method m : b) {
        Type[] pType = m.getGenericParameterTypes();
        if(pType.length==0){
            continue;
        }
        /**
         * Create new array to hold value of parameters
         */
        Object[] params = new Object[pType.length];

        for (int i = 0; i < pType.length; i++) {
            System.out.println("The Arguments :" + pType[i] + " Arguments Order :" + i);
            if (pType[i].equals(String.class)) {
                params[i] = "Hello";

            } else if (pType[i].equals(int.class)) {
                params[i] = 21;                 
            }

        }
        m.setAccessible(true);
        /**
         * Invoke method with all paramtters.
         */
        m.invoke(obj, params);
    }

    return obj;
}

You have a setter for name1 that takes 3 strings as parameters, but in your getBean method, you are invoking it dynmaically using m.invoke(obj,"Hello"); 您有一个name1setter ,它使用3字符串作为参数,但是在getBean方法中,您正在使用m.invoke(obj,"Hello");调用它m.invoke(obj,"Hello"); , that means, that you are trying to invoke a method named setName1 with only one parameter, and this method does not exist. ,这意味着您试图仅通过一个参数调用名为setName1的方法,而该方法不存在。

For explanation purposes, I edited it to m.invoke(obj, "Hello","Hello","Hello"); 为了说明起见,我将其编辑为m.invoke(obj, "Hello","Hello","Hello"); and it works. 而且有效。

The same goes for the setAge1 : m.invoke(obj, 21,21); setAge1也是setAge1m.invoke(obj, 21,21);

The goal is that, you have to provide as more objects to the invoke method as the number of the parameters you have declared in the method 目标是,必须为invoke方法提供的对象数量要比在该方法中声明的参数数量更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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