大家好,欢迎来到IT知识分享网。
实例化对象,都不陌生。大家知道几种呢?
接下来就温习下对象实例化的7种方式:
- 1、用new语句创建对象
Test test = new Test();- 2、用对象的clone()方法。需要实现Cloneable,并重写clone方法。
// 1、实现Cloneable接口 public class Test implements Cloneable{ private int a; public int getA() { return a; } public void setA(int a) { this.a = a; } // 2、重写clone方法 @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }Test test = new Test(); // 3、从一个对象中clone一个新的对象 Test test2 = (Test) test1.clone();- 3、用Class静态方法 Class.forName
Class<?> calzz = Class.forName("org.test.Test"); Test test3 = (Test) calzz.newInstance();- 4、使用ClassLoader实例的.loadClass
// 获取classload 可以通过:1、Xxx.class.getClassLoader(); // 也可用2、 Thread.currentThread().getContextClassLoader(); // 或者 3、ClassLoader.getSystemClassLoader(); ClassLoader cl = Main.class.getClassLoader(); Class<?> cls = cl.loadClass("org.test.Test"); Test test4 = (Test) cls.newInstance();- 5、使用Constructor类的newInstance方法
Constructor<Test> constructor = Test.class.getConstructor(); Test test5 = constructor.newInstance(null);- 6、使用反序列化
除了采用jdk的序列化和反序列化,也可以通过第三方工具转为xml,json等进行
// 实现Serializable接口 public class Test implements Serializable { private int a; public int getA() { return a; } public void setA(int a) { this.a = a; } }
// 1、序列化 FileOutputStream fileOutputStream = new FileOutputStream("temp"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(test1); fileOutputStream.close(); // 2、反序列化 FileInputStream fileInputStream = new FileInputStream("temp"); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); Test test6 = (Test) objectInputStream.readObject();
- 7、使用JavaBeans的BeanContext实例化
BeanContext beanContext = new BeanContextSupport(); Test test7 = (Test) beanContext.instantiateChild("org.test.Test");
以上就是Java对象实例化的7种方式,还有其他方式,欢迎评论区见。
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/115839.html