Domanda

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
È stato utile?

Soluzione

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

Altri suggerimenti

Set it to the name of the field:

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

Documentation here

The method signature of setProperty()

public static void setProperty(Object bean,
                               String name,
                               Object value)
                        throws IllegalAccessException,
                               InvocationTargetException

    Parameters:
        bean - Bean on which setting is to be performed
        name - Property name (can be nested/indexed/mapped/combo)
        value - Value to be set 

name is Property name "te" not "setTe".

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

The class must be public, and provide a public constructor that accepts no arguments. This allows tools and applications to dynamically create new instances of your bean, without necessarily knowing what Java class name will be used ahead of time, like this:

     String className = ...;
     Class beanClass = Class.forName(className);
     Object beanInstance = beanClass.newInstance();

get from http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/apidocs/org/apache/commons/beanutils/package-summary.html#FAQ.property

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top