- 使用new直接創建
- 使用java反射創建
- 調用clone()方法,進行實例的拷貝
- 通過反序列化類獲取
使用new直接創建
Test t = new Test();
使用java反射創建
1、獲取Class對象的三種方式
- 公有屬性class
Class<?> clazz = Test.class;
- 方法getClass()
Test t = new Test();
Class<?> clazz = t.getClass();
- Class.forName()
Class<?> clazz = Class.forName("com.xx.Test");
2、通過反射實例化對象的兩種方式
- Class.newInstance()
Class<?> clazz = Class.forName("com.xx.Test");
Test t = (Test) clazz.newInstance();
- Constructor.newInstance()
Constructor[] constructor = Test.class.getConstructors();
Test t = (Test) constructor[0].newInstance(null);
備注說明:枚舉類型不支持反射來實現,因此java推薦使用enum實現單例模式
if ((clazz.getModifiers() & Modifier.ENUM) != 0)
throw new IllegalArgumentException("Cannot reflectively create enum objects");
調用clone()方法,進行實例的拷貝
Test t = new Test();
Test t2 = (Test) t.clone();
通過反序列化類獲取
通過ObjectInputStream的readObject()的方法