XaolingBao
XaolingBao

Reputation: 1044

BeanUtils.copyProperties(subclass,superclass) returns null for subclass field values

I was looking up how to copy a superclass object's data to a subclass.

I found this thread How to copy superclass object values to subclass object values? which links to another thread that says to use BeanUtils.copyProperties.

I used the above code

BeanUtils.copyProperties(subclass,superclass);

but when I try to print values from the subclass, I get null for the values

        this.face = new FaceData[faces];
        this.f = new FaceSubData[faces];

        for(int i = 0; i < faces; i++)
        {                     


            this.face = //somevalue
            this.f[i] = new FaceSubData();
            try
            {
                BeanUtils.copyProperties(f[i], face[i]);
                System.out.println(f[i].x);
            }
            catch (IllegalAccessException | InvocationTargetException ex) 
            {
                Logger.getLogger(PlanHead.class.getName()).log(Level.SEVERE, null, ex);
            }

if I print f[i].x I get null, but if I do face[i].x I get all the values.

Basically the subclass gets all of the values from the superclass, and adds a few extra bits of data I need to work with.

Am I doing something wrong...?

Also, there is a point in the loop, if last and current array value are the same, then I only need to copy the properties from the previous subclass, to the current subclass.. I'm curious if this will copy all of the properties, or just the few from the subclass itself? I would assume everything, but from the issue now I'm not too sure...

Thanks.

Upvotes: 0

Views: 5022

Answers (1)

malaguna
malaguna

Reputation: 4233

As you state in your demo code, you access properties not accessors, and BeanUtils does not access properties but instead accessors. If you don't have getters/setters for your properties, sure BeanUtils is not copying anything.

On the other hand, I would like to advise you that Javadoc of BeanUtils.copyProperties (well this one points to BeanUtilsBean.copyProperties) states the following:

If you know that no type conversions are required, the copyProperties() method in PropertyUtils will execute faster than this method.

So as you are copying from superclass to subclass, I guess there are no type conversion, so reconsider using PropertyUtils.copyProperties.

Upvotes: 3

Related Questions