public class ReflectUtil { public static Object setFieldValueDefault(Object target, String fname, Class ftype, Object fvalue) { if (target == null || fname == null || "".equals(fname) || (fvalue != null && !ftype .isAssignableFrom(fvalue.getClass()))) { return target; } Class clazz = target.getClass(); Field[] fs = clazz.getDeclaredFields(); try { for (int i = 0; i < fs.length; i++) { if (fname.toLowerCase().equals(fs[i].getName().toLowerCase())) { Method method = clazz.getDeclaredMethod("set" + Character.toUpperCase(fs[i].getName().charAt(0)) + fs[i].getName().substring(1), String.class); if (!Modifier.isPublic(method.getModifiers())) { method.setAccessible(true); } method.invoke(target, fvalue); } } } catch (Exception me) { try { Field field = clazz.getDeclaredField(fname); if (!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } field.set(target, fvalue); } catch (Exception fe) { fe.getStackTrace(); } } return target; }
public static Object setFieldValue(Object target, String fname, Class ftype,
Object fvalue) { if (target == null || fname == null || "".equals(fname) || (fvalue != null && !ftype .isAssignableFrom(fvalue.getClass()))) { return target; } Class clazz = target.getClass(); Field[] fs = clazz.getDeclaredFields(); try { Method method = clazz.getDeclaredMethod("set" + Character.toUpperCase(fname.charAt(0)) + fname.substring(1), String.class); if (!Modifier.isPublic(method.getModifiers())) { method.setAccessible(true); } method.invoke(target, fvalue); } catch (Exception me) { try { Field field = clazz.getDeclaredField(fname); if (!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } field.set(target, fvalue); } catch (Exception fe) { fe.getStackTrace(); } } return target; }public static Object getFieldValue(Object target, String fname, Class ftype) {
if (target == null || fname == null || "".equals(fname)) { return null; } Class clazz = target.getClass(); try { Method method = clazz.getDeclaredMethod("get" + Character.toUpperCase(fname.charAt(0)) + fname.substring(1), ftype); if (!Modifier.isPublic(method.getModifiers())) { method.setAccessible(true); } return method.invoke(target); } catch (Exception me) { try { Field field = clazz.getDeclaredField(fname); if (!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } return field.get(target); } catch (Exception fe) { fe.getStackTrace(); } } return null; } }