JAVA和Nginx 教程大全

网站首页 > 精选教程 正文

Java对象实例化的7种方式

wys521 2024-12-26 13:18:29 精选教程 25 ℃ 0 评论

实例化对象,都不陌生。大家?知道?几种?呢??

接下来就温习下对象实例化的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种方式,还有其他方式,欢迎评论区见。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表