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

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

问题描述

前几天与同事谈过此事。

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

显而易见的是使用构造函数,但还有其他什么方法?

There's the obvious which is to use a constructor, but what other ways are 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天全站免登陆