【Java】Java获取对象的四种方式

1、new关键字

User user = new User();

2、反射

Student student = (Student) Class.forName(“com.gsl.src.Student”) .newInstance();
或者
Student stu = Student.class.newInstance() ;

3、克隆(必须实现Cloneable接口,重写clone方法,clone方法默认是浅拷贝,需要改成深拷贝)

Student stu2 = student.clone () ;

4、反序列化

0bjectInputStream in = new ObjectInputStream (new FileInputStream(“data.obj”)); 
Student stu3 =(Student)in.readObject () ;

 

posted @ 2021-08-08 20:55  CEO雷总  阅读(527)  评论(0编辑  收藏  举报