Learning is not so utilitarian, two brothers with you from a higher dimension of easy to read source ~

You’ve probably seen a lot of articles written about Java reflection, but if you come across reflection in the process of reading the source code, have you ever wondered why you use it?

This article will take a look at a practical example of Java reflection in Nacos. This article is not only an analysis of knowledge points, but also an analysis of Nacos design level.

Reflection mechanism practices in Nacos

Let’s first introduce the background to the use of Nacos reflection mechanism.

In the nacos-client project, NamingService can be obtained through NacosFactory, and then NamingService can be used to register service instances:

NamingService namingService = NacosFactory.createNamingService(properties);
namingService.registerInstance("nacos.test.1", instance);
Copy the code

In NacosFactory, NamingService is created based on NamingFactory:

public static NamingService createNamingService(Properties properties) throws NacosException {
    return NamingFactory.createNamingService(properties);
}
Copy the code

NamingFactory creates part of code as follows:

public static NamingService createNamingService(Properties properties) throws NacosException {
    try {
        Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService");
        Constructor constructor = driverImplClass.getConstructor(Properties.class);
        return (NamingService) constructor.newInstance(properties);
    } catch (Throwable e) {
        throw new NacosException(NacosException.CLIENT_INVALID_PARAM, e);
    }
}
Copy the code

At this point, we finally see the use of reflection. We get the Class object from the Class#forName method, and then we get the constructor to create the instance.

If that’s all you see when you read the source code, you may be missing out on some interesting design and things. Have you ever wondered, why do we use reflexes here? Why don’t you just new an object?

Before answering these questions, let’s take a quick look at the Java reflection mechanism.

Java reflection mechanism

Here from the basic concept, principle, simple practice.

Introduction to Java Reflection

Java is a preprogrammed language, and the types of objects are determined at compile time. Some classes may need to be loaded dynamically while the program is running, but they are not used before, so they are not loaded into the JVM. When needed, reflection allows you to dynamically create an object at runtime and call its properties or methods without having to know who the running object is at compile time.

The core of the Java reflection mechanism is the ability to manipulate the properties and methods of a class or object by dynamically loading the class while the program is running and getting the details of the class.

Pros and cons of Java reflection

Advantages of Java reflection:

  • Increase the flexibility of the program, avoid writing the program dead in the code;
  • The code is concise, the code reuse rate is improved, the external call is convenient;
  • For any class, you can know all the properties and methods of that class. You can call any method on any object;

The principle of reflection

Before we get to the basics of reflection, we need to know that after a Java program is compiled, the basic meta information of all classes contained in class files is loaded into JVM memory as class classes. A Class can be understood as a Class describing a Class. Each Class object represents the basic meta information of a specific Class. Reflection is based on Class objects, which store all the information about the Class.

We do not extend the steps within the JVM here. The important thing to understand is that a Class object is an object generated after the JVM loads a.class file, and the reflection mechanism provides access to this object, based on which property access or object construction can be performed. This step takes place during runtime.

The basic use of reflection

There are three common ways to use reflection:

Class CLZ = class.forname (" java.lang.string "); Class CLZ = class.forname (" java.lang.string "); Class CLZ = string.class; class CLZ = string.class; String STR = new String("Hello"); String STR = new String("Hello"); Class clz = str.getClass();Copy the code

The first of the three methods is commonly used. String arguments can be passed or written in the configuration file. The second requires importing a class package. The dependencies are so strong that if you don’t import the package, you’ll throw a compilation error. What’s the use of reflection when you have a third kind of object.

So, usually when we study, we know a lot of different ways, but when we really use, we still need to choose according to the situation. The source code of Nacos uses the first way.

I won’t expand on the use of other apis for reflection here, but let’s get back to the topic and think about why Nacos uses reflection and why it does it in the first way.

Analysis of Nacos reflection mechanism

Before we begin our analysis, let’s look at the project structure. First, the nacos-client project depends on the NACOS-AIP project, and NamingFactory and NamingService are in the nacos-API project. And specific the com object class is instantiated. Alibaba. Nacos. Client. Naming. NacosNamingService, obviously in nacos – of the client.

As we can see from the figure above, NamingFactory implements the NamingService instantiation logic, but the Nacos-API project does not have NacoNamingService, so the other two methods mentioned above cannot be used. It can only be implemented using the class.forname method.

In fact, the design here is similar to the database driver. Nacos-api defines an interface through NamingService, which is defined as a standard. Nacos-client implements this standard, and must meet two conditions: first, the implementation class from NamingService; Second, the full pathname of the class should be the same as the name of the object instantiated in NamingFactory.

If you think about the usage of Nacos, isn’t it one of the typical use scenarios of reflection mechanism?

summary

In this paper, the reflection mechanism of Nacos, in-depth thinking and questions, and a brief introduction of Java reflection mechanism. Finally, the Nacos project structure is further analyzed to answer the initial questions. Do you read source code this way? Did you learn? Get on the bus! Follow-up more dry goods output.

If you have any questions or want to discuss the content of the article, please contact me (wechat: Zhuan2quan, remarks Nacos), if you think the writing is good, worth learning together, then pay attention to it.

Nacos series of articles

  • 01 “Learn Nacos with two brothers” the first Nacos client service registration source code analysis”

  • Ext-01 “Learn Nacos with two brothers” Ext-01 article to see how Nacos is live to learn to use the simple factory mode!

  • Ext-02 “Learn Nacos from two senior brothers” Ext-02 interviewers asked about the factory model, did you understand it correctly?

Author of SpringBoot Tech Insider, loves to delve into technology and write about it.

Official account: “Program New Horizon”, the official account of the blogger, welcome to follow ~

Technical exchange: please contact the blogger wechat id: Zhuan2quan