Java Reflection-2021 Interview Questions Series Tutorial (with answer analysis)-Vernacular interpretation-JavaPub version

Java Reflection-2021 Interview Questions Series Tutorial (with answer analysis)-Vernacular interpretation-JavaPub version

Preface

Preface

No matter how tall the framework is, it also requires a solid foundation to play, and high-frequency interview questions are the key to high-frequency actual combat in the foundation.

Suitable for readers

Java learners and enthusiasts, technical people with certain work experience, prospective interviewers, etc.

Read suggestions

This tutorial is a series of tutorials, including Java basics, JVM, container, multithreading, reflection, exception, network, object copy, JavaWeb, design patterns, Spring-Spring MVC, Spring Boot / Spring Cloud, Mybatis / Hibernate, Kafka, RocketMQ, Zookeeper, MySQL, Redis, Elasticsearch, Lucene. Subscribe not to get lost, 2021 Orly gives.

JavaPub knowledge list

微信搜:JavaPub,阅读全套系列面试题教程

wx

[tap]

topic

Preface

1. What is reflection?

Baidu Encyclopedia:

Java's reflection mechanism means that in the running state of the program, you can construct an object of any class, you can understand the class to which any object belongs, you can understand the member variables and methods of any class, and you can call any object's Properties and methods. The function of dynamically acquiring program information and dynamically calling objects is called the reflection mechanism of Java language. Reflection is seen as the key to dynamic languages.

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:

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

JavaPub reference giant: https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html

At this point, if you still have some doubts about Java reflection, I will go back to the JavaPub official account and give a more detailed explanation.

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

Serialization and deserialization are the most basic knowledge points in Java, and it is easy to be forgotten by everyone. Although you use it every day, you may not be able to clearly explain it. I believe that many friends only have a few concepts and keywords (Serializable). If you inquire about how serialization and deserialization are implemented, usage scenarios, etc., you may be at a loss. Every time I, as an interviewer, examine the basics of Java, I usually ask about the knowledge of serialization and deserialization to measure its Java basics. When asked what is Java serialization? What is deserialization? In what scenarios will it be used? If you don’t use it, what problems will arise? Generally, everyone’s answer is just a few simple concepts. Some applicants who have worked for several years can't even explain the concept clearly and look boring.

What is serialization and deserialization

序列化是指将Java对象转换为字节序列的过程,而反序列化则是将字节序列转换为Java对象的过程。

Java对象序列化是将实现了 Serializable 接口的对象转换成一个字节序列,能够通过网络传输、文件存储等方式传输 ,传输过程中却不必担心数据在不同机器、不同环境下发生改变,也不必关心字节的顺序或其他任何细节,并能够在以后将这个字节序列完全恢复为原来的对象(恢复这一过程称之为反序列化)。

对象的序列化是非常有趣的,因为利用它可以实现轻量级持久性,“持久性”意味着一个对象的生存周期不单单取决于程序是否正在运行,它可以生存于程序的调用之间。通过将一个序列化对象写入磁盘,然后在重新调用程序时恢复该对象,从而达到实现对象的持久性的效果。

本质上讲,序列化就是把实体对象状态按照一定的格式写入到有序字节流,反序列化就是从有序字节流重建对象,恢复对象状态。

Simply put, it is to save the state of various objects in memory (that is, instance variables, not methods), and to read 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

  1. When you want to save the object state in memory to a file or database;
  2. When you want to use sockets to transfer objects on the network;
  3. When you want to transfer objects through RMI;

Why you need to use serialization and deserialization

We know that during remote communication between different processes/programs, various types of data can be sent to each other, including text, pictures, audio, video, etc., and these data will be transmitted on the network in the form of a binary sequence.

So when two Java processes communicate, can the object transfer between processes be realized? Of course it is possible! How to do it? This requires the use of Java serialization and deserialization. The sender needs to convert this Java object into a byte sequence, and then transmit it on the network, and the receiver needs to restore the Java object from the byte sequence.

After we understand why we need to use Java serialization and deserialization, we naturally think of the benefits of Java serialization:

Realize the persistence of data. Through serialization, the data can be permanently saved to the hard disk (such as: stored in a file) to achieve permanent preservation of the object.
Use serialization to achieve remote communication, that is, the ability to transmit objects on the network.

JavaPub reference giant: https://xcbeyond.blog.csdn.net/article/details/100046212

3. What is a dynamic proxy? What are the applications?

Dynamic proxy: at runtime, create a target class, you can call and extend the method of the target class.

The way to realize dynamics in Java: dynamic proxy in JDK and Java class library CGLib.

Application scenarios such as:

  • Count the time consumption of each api request

  • Unified log output

  • Verify whether the called api has been logged in and authorized authentication

  • Spring's AOP function module uses dynamic proxy mechanism to realize aspect programming

JavaPub reference giant: https://www.cnblogs.com/aheizi/p/4861422.html

4. How to implement dynamic proxy?

In the Java field, there are two commonly used dynamic proxy implementation methods, one is to use the JDK reflection mechanism to generate the proxy, and the other is to use the CGLIB proxy.

The JDK proxy must provide an interface, but CGLIB does not need to proxy the class directly. Examples are given below.

1. JDK dynamic proxy:

public interface People {
    public void sayHello();
}
public class Chinese implements People {

    @Override
    public void sayHello() {
        System.out.println("Chinese say hello.");
    }
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class PeopleInvocationHandler implements InvocationHandler{

    private Object peolple;

    Intermediary(Object people){
        this.people = people;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {        Object invoke = method.invoke(people, args);
        System.out.println("-------- end ---------");
        return invoke;
    }
}
import java.lang.reflect.Proxy;

public class Test {
    public static void main(String[] args) {
        People chinese = new People();
        PeopleInvocationHandler invocationHandler = new PeopleInvocationHandler(chinese);
        People proxy = (People) Proxy.newProxyInstance(chinese.getClass().getClassLoader(), chinese.getClass().getInterfaces(), invocationHandler);
        proxy.sayHello();
    }
}

2. CGLIB dynamic agent

需要引入CGLIB相关Jar包

public class Chinese {
    public void sayHello(){
        System.out.println("Chinese say hello");
    }
}
import java.lang.reflect.Method;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class ChinesePoxy implements MethodInterceptor {

    @Override
    public Object intercept(Object object, Method method, Object[] args,MethodProxy methodProxy) throws Throwable {
        Object intercept = methodProxy.invokeSuper(object, args);
     System.out.println("-------- end ---------");
    return intercept; 
  } 
}
import net.sf.cglib.proxy.Enhancer;

public class Test {
    public static void main(String[] args) {
        ChineseProxy chineseProxy = new ChineseProxy();

        Enhancer enhancer = new Enhancer();  
        enhancer.setSuperclass(Chinese.class);
        enhancer.setCallback(chineseProxy);

        Chinese proxy = (Chinese) enhancer.create();
        proxy.sayHello();
    }
}

JavaPub reference giant: https://www.cnblogs.com/xifengxiaoma/p/9377261.html

How to use Java's reflection?

  • Create an object with a fully qualified class name
  1. Class.forName("Full class name"); For example: the com.mysql.jdbc.Driver Driver class has been loaded into the jvm, and the initialization of the class is complete.

  2. Class name.class; Get Class<? > clz object

  3. Object.getClass();
  • Get the constructor object, and create an object through the constructor new
  1. Clazz.getConstructor([String.class]);
  2. Con.newInstance([Parameter]);
  • Create an instance object through the class object (it is equivalent to the new class name () no-argument constructor)
  1. Cls.newInstance();
  • Obtain an attribute object through the class object
  1. Field c=cls.getFields(): Get all public (public) fields of a certain class, including fields in the parent class.

  2. Field c=cls.getDeclaredFields(): Get all declared fields of a certain class, including public, private, and protected, but not including the declared fields of the parent class
  • Obtain a method object through the class object
  1. Cls.getMethod("method name",class……parameaType); (only public ones can be obtained)

  2. Cls.getDeclareMethod("method name"); (Get arbitrarily decorated method, cannot execute private)

  3. M.setAccessible(true); (make private methods executable)
  • Let the method execute
  1. Method.invoke(obj instance object, obj variable parameter);-----(has a return value)

2021 面试题,认准 JavaPub。

Guess you like

Origin blog.51cto.com/14747927/2625652