1

What should be a best way to create key/value pairs for all the string instance variables of a class? Is there any library exists doing such a task?

I am doing the same using a reflection based backward look-up. But it seems doing to much work.

For example:

I have a class

public class Account implements ManagedEntity {

private String accountNumber;

public Account(String accountNumber) {
    this.accountNumber = accountNumber;
}
}

If an instance of Account class is created like blelow, Account ac = new Account("abc");

The output map should be like: [{"accountNumber", "abc"}].

Vijay Shanker Dubey
  • 4,308
  • 6
  • 32
  • 49

2 Answers2

2

As Peter Lawrey already pointed out in one of the comments, if you are looking for a library that can do that transformation for you then one possible answer is Apache Commons BeanUtils:

You could use the BeanUtils class from that library:

Account account = new Account("abc");
Map accountMap = new HashMap();
BeanUtils.populate(account, accountMap);

Or using the BeanMap implementation it would be even easier:

Account account = new Account("abc");
Map accountMap = new BeanMap(account);
Alonso Dominguez
  • 7,750
  • 1
  • 27
  • 37
0

Like mentioned by Peter Lawrey and here, it would be like

Account ac = new Account("abc");
Map<String, Object> properties = BeanUtils.describe(ac);

To limit it to String properties, you could use a BeanUtilsBean instance, passing a subclass of ConvertUtilsBean to the constructor. The subclass overrides the lookup method, which returns null if the class isn't String.

Community
  • 1
  • 1
Zeemee
  • 10,486
  • 14
  • 51
  • 81