public class Test
{
public static void main(String[] args)
{
SonClass sc=new SonClass();
sc.aa=12;
sc.ee=34;
sc.m="aaa";
try {
SonClass b=(SonClass)clone(sc);
System.out.println(b.aa);
System.out.println(b.ee);
System.out.println(b.m);
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static ArrayList<Field> link(Field[] aa,Field[] bb)
{
ArrayList<Field> fs=new ArrayList<Field>();
for(Field f:bb)
fs.add(f);
for(Field f:aa)
{
boolean flag=false;
String str=f.getName();
for(Field j:bb)
{
if(j.getName().equals(str))
{
flag=true;
break;
}
}
if(!flag)fs.add(f);
}
return fs;
}
public static Field[] getAllFields(Object arg)
{
Class cl=arg.getClass();
ArrayList<Field> fs=link(cl.getFields(),cl.getDeclaredFields());
return fs.toArray(new Field[fs.size()]);
}
public static Object clone (Object a)throws CloneNotSupportedException,IllegalAccessException,InstantiationException
{
Class cl=a.getClass();
Object b=null;
b = cl.newInstance();
Field[] fa=getAllFields(a);
AccessibleObject.setAccessible(fa,true);
for(Field f:fa)
{
if(f.getType().isPrimitive())f.set(b,f.get(a));
else f.set(b, clone(f));
}
return b;
}
}
报了个java.lang.InstantiationException错误,但是不明白为什么不能实例化