创建对象的方式
1.通过new()对象
示例:
StudentExt studentExt = new StudentExt();
2.Class.newInstance()反射
Class<?> cls=null;
StudentExt studentExt1=null;
try {
/*对象的权限位置*/
cls=Class.forName("com.kx.common.entity.StudentExt");
studentExt1=(StudentExt)cls.newInstance();
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
3.Constructor类的newInstance()
Constructor con= null;
try {
con = cls.getConstructor(String.class);
/*此处的Instance可传带参数*/
StudentExt studentExt2= (StudentExt) con.newInstance("clazzName");
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
4.调用对象的clone方法
/*需实例化Cloneable 接口*/
StudentExt studentExt2 = new StudentExt();
StudentExt studentExt3 = null;
studentExt2 = (StudentExt) studentExt3.clone();
5.运用反序列化
ObjectOutputStream out = new ObjectOutputStream (new
FileOutputStream("D:/####.txt"));
//序列化对象
out.writeObject(studentExt2);
out.close();
//反序列化对象
ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:/####.txt"));
StudentExt user4 = (StudentExt) in.readObject();
System.out.println("反序列化user:" + user4);
in.close();
6.第三方库Objenesis
参照网址: