I'm trying to set a property in a bean and I cant seem to get BeanUtils to work...

Heres a small example of the problem I am getting.

public class Example
{
    public static void main(String[] args)
    {
        Example example = new Example();
        example.run();
    }
    public void run()
    {
        try
        {
            Bean bean = new Bean();
            BeanUtils.setProperty(bean, "name", "myName");
            System.out.println(bean.getName());
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
    private class Bean
    {
        private String name;

        public String getName()
        {
            return name;
        }

        public void setName(String name)
        {
            this.name = name;
        }
    }
}

When I run this I get an InvocationTargetException, saying "Cannot set name" Also when I the property string to "Name", I don't get the error, BUT the name isn't set.

Can anyone point me in the right direction as to where I'm going wrong?

Accepted Answer

take the private attribute off of the Bean class. As BeanUtils is using reflection, it can't get access to the method 'setName'. The reason why you can access a private inner class normally, is that the java compiler does special tricks to allow you access. But since BeanUtils isn't using those tricks, it can't.

Written by MeBigFatGuy
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki