java - Setting a value into a object using reflection -


i have object has lot of attributes, each 1 it's getter , setter. each attribute has non primitive type, don't know @ runtime.

for example, have this:

public class a{      private typea attr1;     private typeb attr2;      public typea getattr1(){ return attr1; }     public typeb getattr2(){ return attr2; }      public void setattr1(typea at){ attr1 = at; }     public void setattr2(typeb at){ attr2 = at; } }  public class typea{     public typea(){         // doesn't matter     } }  public class typeb{     public typeb(){         // doesn't matter     } } 

so, using reflection, obtained setter method attribute. setting value in standard way this:

a test = new a(); a.setattr1(new typea()); 

but how can using reflection? got setattr1() method using reflection, don't know how create new typea object inserted in setter.

use class#newinstance().

class<typea> cls = typea.class; typea typea = cls.newinstance(); 

or, in specific case when have determine type of method parameter:

class<?> cls = settermethod.getparametertypes()[0]; object value = cls.newinstance(); settermethod.invoke(bean, value); 

you can learn more reflection in sun tutorial on subject. said, classnames ought start uppercase. i've corrected in above example.

by way, instead of reinventing javabean reflection wheel, may find 1 of tools mentioned here useful well.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -