Reflection (four)

Reflection (four)

57. What is reflection?

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

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:

  • Judge 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 method at runtime.

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

Simply put, it is to save the state of various objects in the 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 for saving object states that should be better than your own, that is serialization.

Under what circumstances need to serialize:

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 ;

59. 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, and so on. 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 well defined, it is dynamically generated. It has the meaning of decoupling, flexibility, and strong scalability.

Application of mobile agent:

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

60. How to implement dynamic proxy?

First, an interface must be defined, 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). Using the InvocationHandler, splicing the source code of the proxy class, compiling it to generate the binary code of the proxy class, loading it with the loader, and instantiating it to generate the proxy object, and finally returning.

Guess you like

Origin blog.csdn.net/xghchina/article/details/114707331