Search code examples
javaannotationslombok

Is there a Lombok annotation to get all fields of an object of a class as an Object array?


I have a class which represents the primary key (which is a composite one) of a database table.

@Value
public class ItemPrimaryKey {
    String compositeKeyColumnA;
    String compositeKeyColumnB;
    String compositeKeyColumnC;
    String compositeKeyColumnD;
}

When I want to read a row from the table by primary key, I should do the following:

jdbcTemplate.query(
    READ_ITEM_BY_PK_QUERY,
    new BeanPropertyRowMapper<>(Item.class),
    itemPrimaryKey.getCompositeKeyColumnA(),
    itemPrimaryKey.getCompositeKeyColumnB(),
    itemPrimaryKey.getCompositeKeyColumnC(),
    itemPrimaryKey.getCompositeKeyColumnD());

However, because the query method of JdbcTemplate takes Object... as its last parameter, I can do the following:

public class ItemPrimaryKey {
    // ...
    public Object[] getForVarArgs() {
        return new Object[] { compositeKeyColumnA, compositeKeyColumnB, compositeKeyColumnC, compositeKeyColumnD };
    }
}
jdbcTemplate.query(
    READ_ITEM_BY_PK_QUERY,
    new BeanPropertyRowMapper<>(Item.class),
    itemPrimaryKey.getForVarArgs());

Since I have the above situation for multiple classes/DB tables, I would like to achieve it with a Lombok annotation, if possible. Is there one that does this?

I have looked through Lombok's documentation, and googled, but I found no such thing. However, maybe there is a configuration for an existing annotation that could still achieve this?


Solution

  • you won't be able to do it with Lombok. If you are looking for alternatives, one way would be to convert the object to a hashmap using jackson, and then get all the keys:

    private static String[] getFieldNames(Object obj) {
        Map<String, Object> map = new ObjectMapper().convertValue(obj, Map.class);
        return map.keySet().toArray();
    }
    

    though, I would rather manually enter the field names in the query, if it is not something that can dynamically change.