Rnet
Rnet

Reputation: 5040

Runtime annotations design and performance

I have a java api which performs an external resource lookup and then maps the values to a Pojo. To do this, the api needs the field names of the Pojo as string values, something like:

public <F> F populatePojoFields(String primaryField, String secondaryField);

This works fine, however passing the pojo field names as String to the api does not feel right. I was able to change this by writing marker annotations for the pojo, so now it is like

public class POJO {
   @Primary //custom marker annotation
   private int mojo;

   @Secondary //custom marker annotation
   private String jojo;
}

String primaryField = getFieldNameUsingReflection(Pojo.class, Primary.class)
String secondryField = getFieldNameUsingReflection(Pojo.class, Secondary.class)

Pojo pojo = populatePojoFields(primaryField, secondaryField);

This way I don't have to keep track of string values, I can just add marker annotations to the Pojo fields. This works fine, but I'm worried about performance. Is this a standard way to do things? as keeping hardcoded string values is more efficient than looking up the field names every time we need to call the api. Is there a better way to do this?

Upvotes: 1

Views: 147

Answers (1)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

If you call getFieldNameUsingReflection often you can think to cache the result of this call. You can use a singleton class with internal Map with a code like the following:

public class SingletonMapPrimarySecondary {
    Map<Class, String> mapPrimary;
    Map<Class, String> mapSecondary;

    // TODO: Handle mapPrimary and mapSecondary creation and singleton pattern

    public String getPrimary(Class clazz) {
        String primary = mapPrimary.get(clazz);
        if (primary == null) {
            primary = getFieldNameUsingReflection(clazz, Primary.class);
            mapPrimary.put(clazz, primary);
        }
        return primary;
    }

    public String getSecondary(Class clazz) {
        // TODO: Similar to getPrimary
    }
}

Upvotes: 2

Related Questions