Code, JavaEE

Java Reflection: Build Command Mappings

The following code has a method that builds a java.util.Map<K,V> for a given Command Type that contains fields and setter method mappings as shown…

 


public class ReflectionTest {
 @Test
 public void testEnumerateClassAttribs() {
 Map<String, Object> fieldMappingsCreateTask = buildFieldNameToSetterMapFor(CreateTask.class);
 System.out.printf("%nCreate Task Mappings: %s", fieldMappingsCreateTask);

Map<String, Object> fieldMappingsCreateProduct = buildFieldNameToSetterMapFor(CreateProduct.class);
 System.out.printf("%nCreate Product Mappings: %s", fieldMappingsCreateProduct);
 }

private Map<String, Object> buildFieldNameToSetterMapFor(Class clazz) {
 Map<String, Object> mappings = new HashMap<>();

Field[] fields = clazz.getDeclaredFields();
 for (int i = 0; i < fields.length; i++) {
 // Build field name
 String fieldName = fields[i].getName();
 //System.out.printf("%nFIELD: %s%n", fieldName);

// Build setter for field name
 String setterMethod = String.format("%nset%s%s", fieldName.substring(0,1).toUpperCase(), fieldName.substring(1));
 //System.out.printf("%nSETTER: %s%n", setterMethod);

// add field name to setter mapping
 mappings.put(fieldName, setterMethod);
 }
 return Collections.unmodifiableMap(mappings);
 }
}

class CreateTask implements Command {
 private String id;
 private String description;
 private Boolean complete;
}

class CreateProduct implements Command {
 private String id;
 private String productName;
 private String description;
 private BigDecimal cost;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s