Don't ask me how Ali and Tencent counterattacked during the interview! The latest common Java interview questions and basic questions (with detailed answers) in 2020 are all sorted out for you

A collection of the latest Java common interview questions in 2020 (4)

Recently, many people around me are asking me questions about interviews with big factories. Therefore, I am also combining the interview questions of myself and my friends to sort out common and basic Java interview questions. The first few collections have been posted on the homepage.

Some of the answers are summarized by myself, and some are collected on the Internet. Don't panic after watching these interviews! If you have more experience, you can share it in the comments. If you have any mistakes, you are welcome to point it out. Please let me know, thank you~

reflection

 44. What is reflection?


Reflection mainly refers to the ability of a program to access, detect and modify its own state or behavior.
Java reflection:

In the Java runtime environment, for any class, can you know what attributes and methods the class has? For any object, can any of its methods be called. The
Java reflection mechanism mainly provides the following functions:

  •   Determine the class to which any object belongs at runtime.
  •   Construct an object of any class at runtime.
  • Judge the member variables and methods of any class at runtime.
  • Call any object's method at runtime.

45. What is java serialization? Under what circumstances need serialization?


Simply put, it is to save the state of various objects in memory (that is, instance variables, not methods), and to read out the saved object state. Although you can use your own various methods to save object states, Java provides you with a mechanism that should be better than your own to save object states, that is serialization.

Under what circumstances need serialization:

a) When you want to save the object state in memory to a file or database;
b) When you want to use sockets to transfer objects on the network;
c) When you want to transfer objects through RMI ;

46. ​​What is a dynamic agent? What are the applications?


Dynamic proxy:

When you want to add some extra processing to a method in a class that implements a certain interface. For example, adding logs, adding transactions, etc. You can create a proxy for this class, so the name suggests is to create a new class. This class not only contains the functions of the original class method, but also adds a new class with additional processing on the original basis. This proxy class is not defined, it is dynamically generated. It has decoupling meaning, flexibility, and strong scalability.

Application of dynamic agent:

  • Spring的AOP
  • Add affairs
  • Add permissions
  • Add log

47. How to implement dynamic proxy?


An interface must be defined first, and an InvocationHandler (passing the object of the class that implements the interface to it) processing class.
There is another tool class Proxy (it is customarily called a proxy class, because calling his newInstance() can generate a proxy object, in fact, it is just a tool class that generates a proxy object). Use the InvocationHandler to splice the source code of the proxy class, compile it to generate the binary code of the proxy class, load it with the loader, instantiate it to generate the proxy object, and finally return.

Object copy

48. Why use cloning?


If you want to process an object, but also want to keep the original data for the next operation, you need to clone. The clone in the Java language is for the instance of the class.

49. How to implement object cloning?


There are two ways:

1). Implement the Cloneable interface and rewrite the clone() method in the Object class;

2). Realize the Serializable interface, realize the real deep cloning through the serialization and deserialization of the object, the code is as follows: the
following is the test code:


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class MyUtil {

    private MyUtil() {
        throw new AssertionError();
    }

    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T clone(T obj) throws Exception {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bout);
        oos.writeObject(obj);

        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bin);
        return (T) ois.readObject();

        // 说明:调用ByteArrayInputStream或ByteArrayOutputStream对象的close方法没有任何意义
        // 这两个基于内存的流只要垃圾回收器清理对象就能够释放资源,这一点不同于对外部资源(如文件流)的释放
    }
}
```

import java.io.Serializable;

/**
 * 人类
 * @author nnngu
 *
 */
class Person implements Serializable {
    private static final long serialVersionUID = -9102017020286042305L;

    private String name;    // 姓名
    private int age;        // 年龄
    private Car car;        // 座驾

    public Person(String name, int age, Car car) {
        this.name = name;
        this.age = age;
        this.car = car;
    }

    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 Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", car=" + car + "]";
    }

}
```

 

/**
 * 小汽车类
 * @author nnngu
 *
 */
class Car implements Serializable {
    private static final long serialVersionUID = -5713945027627603702L;

    private String brand;       // 品牌
    private int maxSpeed;       // 最高时速

    public Car(String brand, int maxSpeed) {
        this.brand = brand;
        this.maxSpeed = maxSpeed;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public int getMaxSpeed() {
        return maxSpeed;
    }

    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    @Override
    public String toString() {
        return "Car [brand=" + brand + ", maxSpeed=" + maxSpeed + "]";
    }

}


 

class CloneTest {

    public static void main(String[] args) {
        try {
            Person p1 = new Person("郭靖", 33, new Car("Benz", 300));
            Person p2 = MyUtil.clone(p1);   // 深度克隆
            p2.getCar().setBrand("BYD");
            // 修改克隆的Person对象p2关联的汽车对象的品牌属性
            // 原来的Person对象p1关联的汽车不会受到任何影响
            // 因为在克隆Person对象时其关联的汽车对象也被克隆了
            System.out.println(p1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

Note: Cloning based on serialization and deserialization is not only deep cloning, but more importantly, through generic restriction, you can check whether the object to be cloned supports serialization. This check is done by the compiler, not at An exception is thrown at runtime. This solution is obviously better than using the clone method of the Object class to clone an object. It is always better to expose the problem at compile time than to leave the problem at runtime.

 50. What is the difference between deep copy and shallow copy?


Shallow copy just copies the reference address of the object. Two objects point to the same memory address, so if any value is modified, the other value will change accordingly. This is a shallow copy (for example: assign())

Deep copy is to copy objects and values, two objects modify any value in the other value will not change, this is deep copy (for example: JSON.parse() and JSON.stringify(), but this method cannot copy functions Types of)

At last

In any case, in addition to the interview skills and experience of interview companies, strong skills and good project experience are also their trump cards and confidence. Core technology sharing of first-tier manufacturers

 It took me a long time to sort out some learning materials. What I posted above is the tip of the iceberg in the materials. I hope I can help you! Click to learn the secret code together: csdn

 

That's it for today's content. I will share more pure dry goods articles in the follow-up, and hope to really help you. Your support is my biggest motivation!

                                                                      

Guess you like

Origin blog.csdn.net/weixin_50333534/article/details/108741273