mercredi 16 janvier 2019

Java - Reflection. Set Value in the setter method multiple argument class object whcih 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.

This My User Bean Class

 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.

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

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.

My case I would know Method Parameter type but have to set the deafult value according to method parameter type.





Aucun commentaire:

Enregistrer un commentaire