美文网首页书评、理财实践、生活感悟IT面试笔试&&面试经验
与哗啦啦的情缘——那个面试问我Java中创建对象有几种方式的le

与哗啦啦的情缘——那个面试问我Java中创建对象有几种方式的le

作者: ArtisticYouth | 来源:发表于2018-03-23 22:12 被阅读29次

17年7月份左右我在G7,偶尔会出去面个试感受下生活,感受下外界是否很难找工作,而我的工作又会是什么样子?

来过哗啦啦,貌似没有笔试题,直接面试的,自我介绍也没准备就直接上了,无疑问的磕磕巴巴。

面试官: 创建对象的方式有几种?
我:那不就new嘛

结果可想而知,直接就回去等结果了~~~

1. 使用new关键字;Employee employee = new Employee();

2. 使用Class类的newInstance():

(1)Employee employee = Class.forName("路径.Employee").newInstance();
(2)Employee employee = Employee.class.newInstance();

3. 使用Constructor类的newInstance():

(1)java.lang.reflect.Construcotr<Employee> constructor = Employee.class.getConstructor(new Class[]{});
    Employee employee = constructor.newInstance();
(2)java.lang.reflect.Construcotr<Employee> constructor = Employee.class.getConstructor(new Class[]{int.class,String.class});
    Employee employee = constructor.newInstance(1,"Lucy");

注意:java.lang.reflect.Construcotr<Employee> constructor = Employee.class.getConstructor(new Class[]{int.class,String.class});和java.lang.reflect.Construcotr<Employee> constructor = Employee.class.getConstructor(new Class[]{Integer.class,String.class});对应的构造参数是不一样的

4. 使用clone()方法【实现Cloneable接口并重写其方法clone()】:

Employee employeeOrigin = new Employee();
Employee employee = employeeOrigin.clone();

5. 使用反序列化方法【实现Serializable】:

File file = new File("employee.txt");
Employee employee1 = new Employee(1,"Lucy");
try {

    ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));
    objectOutputStream.writeObject(employee1);
    objectOutputStream.close();
    System.out.println("employee1: "+employee1);
} catch (IOException e) {
    System.out.println("writeObjectError: "+e);
}

try {
    ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file));
    Employee employee2 = (Employee) objectInputStream.readObject();
    objectInputStream.close();
    System.out.println("employee2: "+employee2);
} catch (IOException | ClassNotFoundException e) {
    System.out.println("readObjectError: "+e);
}

中午偶然看到了他,来到了我对面同事的旁边让帮忙查问题;
侧面了解到是另一个部门的leader~~~

相关文章

网友评论

    本文标题:与哗啦啦的情缘——那个面试问我Java中创建对象有几种方式的le

    本文链接:https://www.haomeiwen.com/subject/tssxcftx.html