我要做的是两个对象中String属性值进行比较.如果属性值不一样,我会做相应的处理.最后将属性值赋值到一个新的相同类型的对象(tmp)中,将tmp对象返回.
如果对象中的属性不是String类型我就不做处理.
我现在遇到的问题是:由于比较的对象的类型不确定,所以方法中,2个对象的类型是泛型.
当我将属性值设置完之后,在外边进行调用的时候,无法将泛型类型进行具体转化.
我在声明泛型对象的时候,用的是Class<? extends Object> ,
请看代码:@SuppressWarnings("unused")
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
// TODO Auto-generated method stubGrandFather w = setWObject();
GrandFather z = setZObject();
try {
Sun sun = (Sun) change(w.getFather().getSun(), z.getFather().getSun(), 1); // 这里就出问题了.无法类型转换,下边都是这种问题.  泛型不是可以自由转换对象的么?为什么这里不可以呢?提示cast出错. 是不是应该用<T>呢?应该如何用呢?
Father fa = (Father) change(w.getFather(), z.getFather(), 1);
Brother bro = (Brother) change(w.getFather().getBrother(), z.getFather().getBrother(), 1);
GrandFather yy = new GrandFather();
yy.getFather().setSun(sun);
yy.getFather().setBrother(bro);
yy.setFather(fa);} catch (NoSuchFieldException | SecurityException | IntrospectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}private static Object change(Object srcObject, Object destObject, int index) throws NoSuchFieldException,
SecurityException, IntrospectionException, InstantiationException, IllegalAccessException {Class<? extends Object> src = srcObject.getClass();  //这里是比较关键的地方,这么设置有问题么?
Class<? extends Object> dest = destObject.getClass();
Object tmpObject = src.newInstance();
Class<? extends Object> tmp = tmpObject.getClass(); //个对象是由参数class新生成的对象,属性值设置之后,将对象返回.               // 中间处理有省略,目的就是将属性值赋值到新生成的一个新的对象中.保留原来两个对象的内容
try {for (int j = 0; j < clan[positon].length; j++) {
String fieldName = clan[positon][j][0];
System.out.println("fieldName == " + fieldName);
String flag = clan[positon][j][index];
System.out.println("flg == " + flag);
Field srcField = src.getDeclaredField(fieldName);
Field destField = dest.getDeclaredField(fieldName);srcField.setAccessible(true);
destField.setAccessible(true);
if (!srcField.getGenericType().toString().equals("class java.lang.String")
|| !destField.getGenericType().toString().equals("class java.lang.String")) {
System.out.println("srcField.getGenericType().toString() " == srcField.getGenericType().toString());
continue;
}
if (flag.equals("1")) {
System.out.println("flag  === 1");
// if (srcField.getType()dest)
PropertyDescriptor pd = new PropertyDescriptor(fieldName, src);
Method srcGetMethod = pd.getReadMethod();
String srcFieldVal = (String) srcGetMethod.invoke(srcObject);pd = new PropertyDescriptor(fieldName, dest);
Method destGetMethod = pd.getReadMethod();
String detsFieldVal = (String) destGetMethod.invoke(destObject);if (!detsFieldVal.equals(srcFieldVal)) {
pd = new PropertyDescriptor(fieldName, tmp);
Method tmpSetMothod = pd.getWriteMethod();
tmpSetMothod.invoke(tmpObject, detsFieldVal);
}
}
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchFieldException
| SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}return tmp;
}