Summary Table

Categories Total Count
PII 0
URL 0
DNS 0
EKL 0
IP 0
PORT 0
VsID 0
CF 0
AI 0
VPD 0
PL 0
Other 0

File Content

package gov.va.med.pbm.ampl.utility;

import java.lang.reflect.Field;

/**
* PropertyReflection is an abstract class which uses reflection to access a properties getter and setter.
*
* @author Ian Meinert
*
*/
public abstract class PropertyReflection {

/**
* The get method accesses the getter of a property using reflection.
*
* @param <V> The property Type
* @param object The object which contains the field
* @param fieldName The property to access the getter for
* @return An object of property Type with value
*/
@SuppressWarnings("unchecked")
public static <V> V get(Object object, String fieldName) {
Class<?> clazz = object.getClass();

while (clazz != null) {
try {
// a field name may have dot notation for accessing a fields class property.
// if that is the case, then get the field object and pass it back through the get method
if (fieldName.contains(".")) {
// Only split into two nodes. If the second node contains dot notation, the get method will be called on the
// next iteration
String[] fieldNameProps = fieldName.split("\\.", 2);

// get the field and make it accessible so we can store the object data
Field field = clazz.getDeclaredField(fieldNameProps[0]);
field.setAccessible(true);

// return another iteration of the get method.
return get(field.get(object), fieldNameProps[1]);

} else {
// get the field and make it accessible so we can store the object data
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);

// return the object in relation to the field
return (V) field.get(object);
}
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}

return null;
}

/**
* The set method accesses the setter of a property using reflection.
*
* @param object The object which contains the field
* @param fieldName The property to access the getter for
* @param fieldValue the value to store in the property
* @return A boolean value of whether or not the value was successfully set
*/
// TODO Remove or uncomment this method. If uncommented, resolve Fortify issue with Access Specifier.
// public static boolean set(Object object, String fieldName, Object fieldValue) {
// Class<?> clazz = object.getClass();
//
// while (clazz != null) {
// try {
// Field field = clazz.getDeclaredField(fieldName);
// field.setAccessible(true);
// field.set(object, fieldValue);
// return true;
// } catch (NoSuchFieldException e) {
// clazz = clazz.getSuperclass();
// } catch (Exception e) {
// throw new IllegalStateException(e);
// }
// }
//
// return false;
// }
}