lundi 16 avril 2018

How to use Reflection if the the Bean class contains Array of class?

The below bean class contains the array of class which is a multivalued attribute.I am trying to dynamically set values to the attributes below using Reflection.

        public class User{
                    private String userId;
                    private NameDetails[] nameDetails ;
                    private ContactDetails contactDetails;

                    public ContactDetails getContactDetails() {
                            return contactDetails;
                    }
                    public String getUserId() {
                            return userId;
                    }
                    public void setUserId(String userId) {
                            this.userId = userId;
                    }        
                    public void setContactDetails(ContactDetails contactDetails) {
                            this.contactDetails = contactDetails;
                    }
                    public NameDetails[] getNameDetails() {
                            return nameDetails;
                    }
                    public void setNameDetails(NameDetails[] nameDetails) {
                            this.nameDetails = nameDetails;
                    } 
            }

        The below code is where we implement reflection and I am not able to set a value to the array.
           {          c=Class.forName(method.getReturnType().getComponentType().getName());
                      Object arr = Array.newInstance(c, 1);                      
                      method = innerFieldType.getMethod("set" + tokens[i], new Class[] { arr.getClass() });                   
                      Object obj = Array.get(arr,0);
                      Array.set(obj, 0, finalRefObject);
                      method.invoke(finalRefObject,Array.get(arr, 0));
           }
"java.lang.IllegalArgumentException: array element type mismatch" is the error 
we get.thanks in advance





Aucun commentaire:

Enregistrer un commentaire