package org.geoserver.ows.util; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ClassProperties { private static final List EMPTY = new ArrayList(0); List methods; List getters; List setters; public ClassProperties(Class clazz) { methods = Arrays.asList(clazz.getMethods()); getters = new ArrayList(); setters = new ArrayList(); for (Method method : methods) { final String name = method.getName(); final Class[] params = method.getParameterTypes(); if(name.startsWith("get") && params.length == 0) { getters.add(method); } else if(name.startsWith("set") && params.length == 1) { setters.add(method); } } // avoid keeping lots of useless empty arrays in memory for // the long term, use just one if(methods.size() == 0) methods = EMPTY; if(getters.size() == 0) getters = EMPTY; if(setters.size() == 0) setters = EMPTY; } public Method setter(String property, Class type) { for (Method setter : setters) { if(setter.getName().substring(3).equalsIgnoreCase(property)) { if(type == null) { return setter; } else { Class target = setter.getParameterTypes()[0]; if(target.isAssignableFrom(type) || (target.isPrimitive() && type == wrapper(target)) || (type.isPrimitive() && target == wrapper(type))) { return setter; } } } } // could not be found, try again with a more lax match String lax = lax(property); if (!lax.equals(property)) { return setter(lax, type); } return null; } public Method getter(String property, Class type) { for (Method getter : getters) { if(getter.getName().substring(3).equalsIgnoreCase(property)) { if(type == null) { return getter; } else { Class target = getter.getReturnType(); if(target.equals(type) || (target.isPrimitive() && type == wrapper(target)) || (type.isPrimitive() && target == wrapper(type))) { return getter; } } } } // could not be found, try again with a more lax match String lax = lax(property); if (!lax.equals(property)) { return getter(lax, type); } return null; } /** * Does some checks on the property name to turn it into a java bean property. *

* Checks include collapsing any "_" characters. *

*/ static String lax(String property) { return property.replaceAll("_", ""); } /** * Returns the wrapper class for a primitive class. * * @param primitive A primtive class, like int.class, double.class, etc... */ static Class wrapper( Class primitive ) { if ( boolean.class == primitive ) { return Boolean.class; } if ( char.class == primitive ) { return Character.class; } if ( byte.class == primitive ) { return Byte.class; } if ( short.class == primitive ) { return Short.class; } if ( int.class == primitive ) { return Integer.class; } if ( long.class == primitive ) { return Long.class; } if ( float.class == primitive ) { return Float.class; } if ( double.class == primitive ) { return Double.class; } return null; } public Method method(String name) { for(Method method : methods) { if(method.getName().equalsIgnoreCase(name)) return method; } return null; } }