/*
* Java中创建对象的方法
*/
public class TestNewObj {
public static void main(String[] args) {
// 第1种方法:new关键字
User user1 = new User();
System.out.println(user1);
// 第2种方法:调用java.lang.Class.newInstance()
try {
User user2 = (User)Class.forName("com.test.obj.User").newInstance();
System.out.println(user2);
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException e) {
e.printStackTrace();
}
// 第3种方法:调用java.lang.reflect.Constructor类的newInstance()
try {
Constructor<User> constructor = User.class.getDeclaredConstructor();
User user3 = (User)constructor.newInstance();
System.out.println(user3);
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException |
IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
// 第4种方法:clone
// 第5种方法:使用反序列化
}
}
* Java中创建对象的方法
*/
public class TestNewObj {
public static void main(String[] args) {
// 第1种方法:new关键字
User user1 = new User();
System.out.println(user1);
// 第2种方法:调用java.lang.Class.newInstance()
try {
User user2 = (User)Class.forName("com.test.obj.User").newInstance();
System.out.println(user2);
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException e) {
e.printStackTrace();
}
// 第3种方法:调用java.lang.reflect.Constructor类的newInstance()
try {
Constructor<User> constructor = User.class.getDeclaredConstructor();
User user3 = (User)constructor.newInstance();
System.out.println(user3);
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException |
IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
// 第4种方法:clone
// 第5种方法:使用反序列化
}
}