1

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Making the Bean class its own upper level class should make it work, right?
As long as it's public, or package protected and in the same package as the Example class, yes.
No that didn't work, I Had the bean class public and in its own java file earlier... I only made it private when I was making a shortened version of my problem for posting here, as opposed to posting loads of unwanted code.
i changed the Bean class to public and did java -classpath .:commons-beanutils.jar:commons-logging.jar Example and it worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.