java BeansUtil 反射原理实现(二)
ods = clazz.getMethods();
if(list==null)
return null;
for(T t : list)
{
Field[] fields = clazz.getDeclaredFields();
K object = null;
try {
object = (K)clazz.newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
for(Field field : fields)
{
String newFieldName = field.getName();
if (stringSet.contains(newFieldName))
continue;
try {
Field oldField = t.getClass().getDeclaredField(field.getName());
} catch (NoSuchFieldException e) {
System.out.println(e.getMessage());
continue;
}
for(Method method : methods)
{
if(Modifier.isPublic(method.getModifiers()))//如果是公共的方法
{
String method_name = method.getName();
if(method_name.startsWith("set"))
{
String setMethodName = method.getName().substring(3).toLowerCase();
if(setMethodName.equals(newFieldName.toLowerCase()))
{
String getMethodName = "";
getMethodName = method.getName().substring(3);
String getName = "get"+getMethodName;
try {
method.invoke(object,t.getClass().getMethod(getName).invoke(t));
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
getMethodName = "is" + method.getName().substring(3);
try {
method.invoke(object,t.getClass().getMethod(getMethodName).invoke(t));
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvocationTargetException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} catch (InvocationTargetException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
}
}
newList.add(object);
}
return newList;
}
}
完工 ,大概得作用相信大家应该都能看懂吧 ,看了看别人的自己改良了一些合适自己用的