Java对象创建的方式
1.使用new关键字
这是最常用也最简单的方式,看看下面这个例子就知道了。
[Java] 纯文本查看 复制代码
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
|
public class Test { private String name; public Test() { } public Test(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static void main(String[] args) { Test t1 = new Test(); Test t2 = new Test("张三"); }} |
2.Class对象的newInstance()方法
还是上面的Test对象,首先我们通过Class.forName()动态的加载类的Class对象,然后通过newInstance()方法获得Test类的对象
[Java] 纯文本查看 复制代码
|
1
2
3
4
5
|
public static void main(String[] args) throws Exception {String className = "org.b3log.solo.util.Test";Class clasz = Class.forName(className);Test t = (Test) clasz.newInstance();} |
3.构造函数对象的newInstance()方法
类Constructor也有newInstance方法,这一点和Class有点像。从它的名字可以看出它与Class的不同,Class是通过类来创建对象,而Constructor则是通过构造器。我们依然使用第一个例子中的Test类。
[Java] 纯文本查看 复制代码
|
1
2
3
4
5
6
7
8
9
|
public static void main(String[] args) throws Exception { Constructor<Test> constructor; try { constructor = Test.class.getConstructor(); Test t = constructor.newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); }} |
4.对象反序列化
使用反序列化来获得类的对象,那么这里必然要用到序列化Serializable接口,所以这里我们将第一个例子中的Test作出一点改变,那就是实现序列化接口。
[Java] 纯文本查看 复制代码
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
public class Test implements Serializable{ private String name; public Test() { } public Test(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static void main(String[] args) throws Exception { String filePath = "sample.txt"; Test t1 = new Test("张三"); try { FileOutputStream fileOutputStream = new FileOutputStream(filePath); ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream); outputStream.writeObject(t1); outputStream.flush(); outputStream.close(); FileInputStream fileInputStream = new FileInputStream(filePath); ObjectInputStream inputStream = new ObjectInputStream(fileInputStream); Test t2 = (Test) inputStream.readObject(); inputStream.close(); System.out.println(t2.getName()); } catch (Exception ee) { ee.printStackTrace(); } }} |
5.Object对象的clone()方法
Object对象中存在clone方法,它的作用是创建一个对象的副本。看下面的例子,这里我们依然使用第一个例子的Test类。
[Java] 纯文本查看 复制代码
|
1
2
3
4
|
public static void main(String[] args) throws Exception {[/align] Test t1 = new Test("张三"); Test t2 = (Test) t1.clone(); System.out.println(t2.getName());} |
更多免费技术资料可关注:annalin1203

浙公网安备 33010602011771号