300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > java构造函数创建对象_java创建对象的5种方式

java构造函数创建对象_java创建对象的5种方式

时间:2023-10-25 12:18:07

相关推荐

java构造函数创建对象_java创建对象的5种方式

1、使用new关键字

2、利用反射手段,调用java.lang.Class或者java.lang.reflect.Constructor类的newInstance()实例方法

3、构造函数的newInstance()方法

4、对象的反序列化

5、对象的clone()方法

下面详细看看这5种方法的简单实现:

1、使用new关键字

public classTest {privateString name;publicTest() {

}publicTest(String name) {this.name =name;

}publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}public static voidmain(String[] args) {

Test t1= newTest();

Test t2= new Test("张三");

}

}

2、利用反射

首先通过Class.forName()动态加载类的class对象,然后通过newInstance()方法获得Test对象,这里使用的是上面的Test对象

public static void main(String[] args) throwsException{

String className="com.qml.test";

Class clasz=Class.forName(className);

Test t=(Test)clasz.newInstance();

}

3、构造函数对象的newInstance()方法

类Constructor也有newInstance方法,这一点和Class有点像。从它的名字可以看出它与Class的不同,Class是通过类来创建对象,而Constructor则是通过构造器。依然使用第一个例子中的Test类。

public static void main(String[] args) throwsException {

Constructorconstructor;try{

constructor= Test.class.getConstructor();

Test t=constructor.newInstance();

}catch (InstantiationException |IllegalAccessException|IllegalArgumentException|InvocationTargetException|NoSuchMethodException|SecurityException e) {

e.printStackTrace();

}

}

4、对象反序列化

继承Serializable接口

public class Test implementsSerializable{privateString name;publicTest() {

}publicTest(String name) {this.name =name;

}publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}public static void main(String[] args) throwsException {

String filePath= "sample.txt";

Test t1= new Test("张三");try{

FileOutputStream fileOutputStream=

newFileOutputStream(filePath);

ObjectOutputStream outputStream=

newObjectOutputStream(fileOutputStream);

outputStream.writeObject(t1);

outputStream.flush();

outputStream.close();

FileInputStream fileInputStream=

newFileInputStream(filePath);

ObjectInputStream inputStream=

newObjectInputStream(fileInputStream);

Test t2=(Test) inputStream.readObject();

inputStream.close();

System.out.println(t2.getName());

}catch(Exception ee) {

ee.printStackTrace();

}

}

}

5、对象的clone()方法

public static void main(String[] args) throwsException {

Test t1= new Test("张三");

Test t2=(Test) t1.clone();

System.out.println(t2.getName());

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。