View on GitHub

ObjectMapper by juzraai

Properties in Java! ;-)

Download this project as a .zip file Download this project as a tar.gz file


Properties in Java! ;-)

1. What's this?

ObjectMapper helps you simplify the handling of nested beans, by providing getter and setter methods which work with property names. So it is basically a lightweight alternative to Spring's BeanWrapper. ObjectMapper has much less functions, but it's small and fast. :-)

2. How to use it?

Assume you have these bean classes:

public class Organization {
    private String name;
    private Address address;

public class Address {
    private String city;
    private String street;
    private String zip;
    public Address() { }

You can easily fill up an organization like this:

import static hu.juranyi.zsolt.objectmapper.ObjectMapper.*;

// ...

Organization org = new Organization();
set(org, "name", "CJ Holding");
set(org, "", "Los Santos");
set(org, "address.street", "Grove Street 2.");
set(org, "", "WTF-42");

assertEquals("Los Santos", get(org, ""));

// if you have proper getters and setters:
assertEquals("Los Santos", org.getAddress().getCity());

You don't have to:

You just need to:

Let's see a more interesting example! Assume you have an extended address class too:

public class AddressEx extends Address {
    private String phone;

Even when the static type of address is Address, you can do this:

set(org, "address", new AddressEx());
set(org, "", "123456789");

assertEquals("123456789", get(org, ""));

get() and set() methods have various parameter lists, and there are also list() methods which list all properties from an Object or Class:

3. How does it work?

ObjectMapper does not store anything, it simply uses Java Reflection API to access the declared fields, retrieve their type and value or set them.

This call:

set(org, "", "Los Santos");

does the same as:

Address a = org.getAddress();
if (null == a) {
    a = new Address();
a.setCity("Los Santos");

And this one:

Object o = get(org, "");

does the same as:

Object o = org.getAddress();
if (null != o) {
    o = ((Address) o).getCity();

So when a property is not readable (e.g. address is null so is not accessible) it drops back null.

If any error occurs when setting a property (e.g. there's no proper constructor or field), set() methods will return false.

4. Limitations

You need to define explicitly a no-parameter constructor in every class that appear as type of properties.

ObjectMapper cannot handle elements of collections. (But maybe in the future :-))

5. Usage examples

With this tool you can easily turn your Object into a Map and back, this can be useful for exporting an Object or many of them into a readable format, e.g. CSV.

I use this tool also for building up an Object from a text matching a regexp, which contains named groups which are actually property names. :-)