003 对象属性Property
public final class PropertyNamer { private PropertyNamer() { // Prevent Instantiation of Static Class } public static String methodToProperty(String name) { if (name.startsWith("is")) { name = name.substring(2); } else if (name.startsWith("get") || name.startsWith("set")) { name = name.substring(3); } else { throw new ReflectionException("Error parsing property name '" + name + "'. Didn't start with 'is', 'get' or 'set'."); } if (name.length() == 1 || (name.length() > 1 && !Character.isUpperCase(name.charAt(1)))) { name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1); } return name; } public static boolean isProperty(String name) { return name.startsWith("get") || name.startsWith("set") || name.startsWith("is"); } public static boolean isGetter(String name) { return name.startsWith("get") || name.startsWith("is"); } public static boolean isSetter(String name) { return name.startsWith("set"); } }
上面的PropertyNamer实际上就是一个工具类,通过方法名获取对应的属性.
实际上,就是我们的javaBean的方式,以此来推断属性的.
public final class PropertyCopier { private PropertyCopier() { // Prevent Instantiation of Static Class } public static void copyBeanProperties(Class<?> type, Object sourceBean, Object destinationBean) { Class<?> parent = type; while (parent != null) { final Field[] fields = parent.getDeclaredFields(); for (Field field : fields) { try { try { field.set(destinationBean, field.get(sourceBean)); } catch (IllegalAccessException e) { if (Reflector.canControlMemberAccessible()) { field.setAccessible(true); field.set(destinationBean, field.get(sourceBean)); } else { throw e; } } } catch (Exception e) { // Nothing useful to do, will only fail on final fields, which will be ignored. } } parent = parent.getSuperclass(); } } }
上面为属性拷贝工具类,实际上就是我们之前使用的BeanCopyUtils的一个简单实现.