A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 wuwei丶 于 2019-10-10 14:12 编辑

1.使用new关键字
这是最常用也最简单的方式,看看下面这个例子就知道了。
[Java] 纯文本查看 复制代码
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] 纯文本查看 复制代码
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] 纯文本查看 复制代码
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] 纯文本查看 复制代码
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] 纯文本查看 复制代码
public static void main(String[] args) throws Exception {[/align]    Test t1 = new Test("张三");
    Test t2 = (Test) t1.clone();
    System.out.println(t2.getName());
}


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马