Encapsulate Reflection Property Calls
Color myCarColor = (Color) new Property(myCar.getClass(), "color").getValue(myCar);
new Property(myCar.getClass(), "color").setValue(myCar, Color.RED);
public class Property {
private final Class klass;
private final String fieldName;
private Class type;
public Property(Class klass, String fieldName) {
if (klass == null) {
throw new IllegalArgumentException("Class could not be null");
}
if (fieldName == null) {
throw new IllegalArgumentException("Fieldname could not be null");
}
this.klass = klass;
this.fieldName = fieldName;
setPropertyType();
}
private void setPropertyType() {
try {
type = klass.getDeclaredField(fieldName).getType();
} catch (NoSuchFieldException e) {
// TODO
e.printStackTrace();
}
}
private String getMethodName() {
if (type == boolean.class) {
return "is" + capitalize(fieldName);
} else {
return "get" + capitalize(fieldName);
}
}
private String setMethodName() {
return "set" + capitalize(fieldName);
}
private String capitalize(String name) {
return Character.toUpperCase(name.charAt(0)) + name.substring(1);
}
public Object getValue(Object instance) {
try {
Method getMethod = instance.getClass().getMethod(getMethodName());
return getMethod.invoke(instance);
} catch (Exception e) {
throw new PropertyNotFoundException(klass, getMethodName());
}
}
public void setValue(Object instance, Object value) {
try {
Method setMethod = instance.getClass().getMethod(setMethodName(), value.getClass());
setMethod.invoke(instance, value);
} catch (Exception e) {
throw new PropertyNotFoundException(klass, setMethodName());
}
}
}