反射初应用
利用反射克隆一个对象
public static <T> T clone(Object obj,Class<T> t){
T newObj = null;
try {
newObj = t.newInstance();
Field[] fields = t.getDeclaredFields();
for (Field f : fields) {
String fname = f.getName();
Class<?> ftype = f.getType();
String setMethodName = "set"+fname.substring(0,1).toUpperCase()+fname.substring(1);
String getMethodName = "get"+fname.substring(0,1).toUpperCase()+fname.substring(1);
if(Objects.equals("boolean",ftype.getName())){
getMethodName = "is"+fname.substring(0,1).toUpperCase()+fname.substring(1);
}
Method methodSet = t.getMethod(setMethodName,ftype);
Method methodGet = t.getMethod(getMethodName);
Object returnVal = methodGet.invoke(obj);
methodSet.invoke(newObj,returnVal);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return newObj;
}
public static <T> T clone1(T obj) throws Exception {
Class<T> clazz = (Class<T>) obj.getClass();
T o = null;
o = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
String name = field.getName();
Class<?> type = field.getType();
String suffix = name.substring(0,1).toUpperCase()+name.substring(1);
String getName = "get"+suffix;
String setName = "set"+suffix;
Method methodGet = clazz.getMethod(getName);
Method methodSet = clazz.getMethod(setName, type);
methodSet.invoke(o,methodGet.invoke(obj));
}
return o;
}
利用反射将map转化成javabean
public static <T> T mapToBean1(Map<String,? super Object> map,Class<T> t)throws Exception{
T instance = t.newInstance();
for (Map.Entry<String, ? super Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
Field field = t.getDeclaredField(key);
field.setAccessible(true);
field.set(instance,value);
}
return instance;
}
public static <T> T mapToBean(Map<String,Object> map, Class<T> t){
T target = null;
try {
target = t.newInstance();
Field[] fields = t.getDeclaredFields();
for (Field f : fields) {
String fieldName = f.getName();
f.setAccessible(true);
f.set(target,map.get(fieldName));
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return target;
}