Copying fields using Apache BeanUtils

49 views
Skip to first unread message

roberto_sc

unread,
Sep 13, 2010, 6:43:40 PM9/13/10
to Protocol Buffers
I have a java class whose attributes have the same name of its message
(.proto) version.
This classes represent the entity "Team" which has a list of "Player".
I'm trying to copy the attributes from the message to the pojo by
using BeanUtils:

Team team = new Team();
Map<FieldDescriptor, Object> m = teamMessage.getAllFields();

Map<String, Object> m2 = new HashMap<String, Object>();
for(FieldDescriptor fd : m.keySet())
m2.put(fd.getName(), m.get(fd));

BeanUtils.populate(team, m2);


System.out.println(team.getName());
System.out.println(team.getPlayerList().get(0).getName());

It generates the following error in the last println:
Exception in thread "main" java.lang.ClassCastException:
proto.DataModel$Player cannot be cast to model.Player
at Main.main(Main.java:49)

That's because the object that was set in the Team.playerList by
BeanUtils was a DataModel.Player (defined in the .proto) instead of a
Player. That is, if the class has an attribute that is another class
(Player, in the case) it won't iterate over this class, it will copy
the object regardless of its type.

So, what's the best way to dynamically copy all atributes from a
message to a pojo?
Thank you.
Reply all
Reply to author
Forward
0 new messages