Use BeanUtils for Setting setter value

19,194

Solution 1

Your class Test should be a public class , Move Test to a own file, make it public and rerun your code.

Solution 2

Set it to the name of the field:

BeanUtils.setProperty(t,"te","teval");

Documentation here

Share:
19,194
sunleo
Author by

sunleo

Enthusiastic java tech Lover!!!! திரை கடலோடியும் திரவியம் தேடு http://www.animatedrecursion.com/intro/introduction.html Reversing a nested loop http://dwite.ca/ How to config Tomcat to serve images from an external folder outside webapps? How is my id being generated with JPA using Hibernate with the Oracle 10g dialect? http://balusc.blogspot.be/2007/04/imageservlet.html

Updated on June 07, 2022

Comments

  • sunleo
    sunleo about 2 years

    I try to set value using setter but null comes.Please help me with this and give if some other better way is there to do.

    import org.apache.commons.beanutils.BeanUtils;
    
    public class TestSetter {
    
        public static void main(String args[]) throws Exception
        {
            Test t = new Test();
            BeanUtils.setProperty(t,"te","teval");
            System.out.println("tevalue :"+t.getTe());
        }
    }
    class Test
    {
        String te;
    
        public String getTe() {
            return te;
        }
    
        public void setTe(String te) {
            this.te = te;
        }
    
    }
    

    Exception :

    Exception in thread "main" java.lang.reflect.InvocationTargetException: Cannot set te
        at org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1025)
        at org.apache.commons.beanutils.BeanUtils.setProperty(BeanUtils.java:313)
        at test.reflection.TestSetter.main(TestSetter.java:10)
    Caused by: java.lang.NoSuchMethodException: Property 'te' has no setter method
        at org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:1746)
        at org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1648)
        at org.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:1677)
        at org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1022)
        ... 2 more
    
  • sunleo
    sunleo over 11 years
    already tried that and it gives this exception Caused by: java.lang.NoSuchMethodException: Property 'te' has no setter method
  • sunleo
    sunleo over 11 years
    I accept and tested but now it gives this error.I updated Question .Pls check.
  • sunleo
    sunleo over 11 years
    Thank you it works problem is with its missing public modifier.
  • MadProgrammer
    MadProgrammer over 11 years
    The test class is not public. BeanUtils doesn't seem capable of parsing protected classes...(ps Otherwise it's right)
  • MadProgrammer
    MadProgrammer over 11 years
    @sunleo The test class is not public, see Jayamohan's answer, then apply Shawn and Pradeep's answers