在 Java 中创建对象的所有不同方法是什么? [英] What are all the different ways to create an object in Java?

查看:26
本文介绍了在 Java 中创建对象的所有不同方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前几天与一位同事就此事进行了交谈.

Had a conversation with a coworker the other day about this.

使用构造函数很明显,但其他方法是什么?

There's the obvious using a constructor, but what are the other ways there?

推荐答案

java中有四种不同的创建对象的方法:

There are four different ways to create objects in java:

A.使用 new 关键字
这是在java中创建对象最常见的方式.几乎 99% 的对象都是通过这种方式创建的.

A. Using new keyword
This is the most common way to create an object in java. Almost 99% of objects are created in this way.

 MyObject object = new MyObject();

B.使用 Class.forName()
如果我们知道类的名称 &如果它有一个公共的默认构造函数,我们可以通过这种方式创建一个对象.

B. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.

MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();

C.使用 clone()
clone() 可用于创建现有对象的副本.

C. Using clone()
The clone() can be used to create a copy of an existing object.

MyObject anotherObject = new MyObject();
MyObject object = (MyObject) anotherObject.clone();

D.使用对象反序列化
对象反序列化只不过是从它的序列化形式创建一个对象.

D. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.

ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();

您可以从这里阅读它们.

这篇关于在 Java 中创建对象的所有不同方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆