Use BeanUtils for Setting setter value

sunleo picture sunleo · Feb 14, 2013 · Viewed 18.4k times · Source

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

Answer

Jayamohan picture Jayamohan · Feb 14, 2013

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