be.objectify.led.PropertyDigger Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of objectify-led Show documentation
Show all versions of objectify-led Show documentation
objectify-led is a small Java library for binding object or class properties at runtime using annotations, reducing boilerplate code.
Values can be taken from the System, from properties files, any arbitrary source in fact, and automatically set on properties.
package be.objectify.led;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Gets the names of properties defined in a class.
*
* @author Steve Chaloner ([email protected]).
*/
public final class PropertyDigger
{
private PropertyDigger()
{
// no-op
}
public enum SortOrder implements PropertySorter
{
NATURAL {
public void sort(List properties)
{
// no-op
}
},
BY_NAME {
public void sort(List properties)
{
Collections.sort(properties,
new Comparator()
{
public int compare(Property propertyA,
Property propertyB)
{
return propertyA.value().compareTo(propertyB.value());
}
});
}
}
}
/**
* Gets the names of properties declared in the given class, listed
* in the order by which reflection finds them.
*
* @param c the class
* @return the property names
*/
public static List getPropertyNames(Class c)
{
return getPropertyNames(c,
SortOrder.NATURAL);
}
/**
* Gets the names of properties declared in the given class.
*
* @param c the class
* @param propertySorter sorts the properties into the required order
* @return the property names
*/
public static List getPropertyNames(Class c,
PropertySorter propertySorter)
{
List properties = getProperties(c,
propertySorter);
List propertyNames = new ArrayList();
for (Property property : properties)
{
propertyNames.add(property.value());
}
return propertyNames;
}
public static List getProperties(Class c)
{
return getProperties(c,
SortOrder.NATURAL);
}
public static List getProperties(Class c,
PropertySorter propertySorter)
{
List properties = new ArrayList();
Field[] fields = c.getDeclaredFields();
for (Field field : fields)
{
if (field.isAnnotationPresent(Property.class))
{
properties.add(field.getAnnotation(Property.class));
}
}
propertySorter.sort(properties);
return properties;
}
}