day12 java创建对象的方法

2019-04-17  本文已影响0人  老婆日向雏田

一、使用new关键字

User user = new User();

二、使用反射机制

//创建方法1
User user = (User)Class.forName("根路径.User").newInstance(); 
//创建方法2(用这个最好)
User user = User.class.newInstance();
Constructor<User> constructor = User.class.getConstructor();
User user = constructor.newInstance();

注:

三、使用clone方法

public class CloneTest implements Cloneable{
    private String name;  
    private int age; 

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public CloneTest(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {
        try {
            CloneTest cloneTest = new CloneTest("wxy",18);
            CloneTest copyClone = (CloneTest) cloneTest.clone();
            System.out.println("newclone:"+cloneTest.getName());
            System.out.println("copyClone:"+copyClone.getName());
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

}

newclone:wxy
copyClone:wxy

四、使用反序列化

注:该文章摘抄自https://blog.csdn.net/w410589502/article/details/56489294

本篇笔记出处@七夏港_f3ef

上一篇下一篇

猜你喜欢

热点阅读