Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the function of Java reflection

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what is the function of Java reflection". In daily operation, I believe that many people have doubts about the role of Java reflection. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "what is the role of Java reflection?" Next, please follow the editor to study!

01. Interpretive language and compiled language

Interpretive languages: do not need to be compiled and translated line by line at run time; code can be modified directly and deployed quickly, but its performance is slightly worse than that of compiled languages; for example, JavaScript and Python

Compiled language: the source code needs to be compiled into machine code by the compiler before it can be executed; if the code needs to be modified after compilation, it needs to be recompiled before execution. Such as C language.

Strictly speaking, Java is also a compiled language, but it is between compiled and interpreted; Java does not generate machine code directly but generates intermediate code: during compilation, the source code is handed over to the compiler to generate class files (bytecode), which only translates and does not put the code into memory to run; when entering the run time, the bytecode is loaded by the Java virtual machine, interpreted into machine language and run.

02. Dynamic and static languages

Dynamic language: it means that the program can change its structure and determine the data type at run time. Whether an object can perform an operation depends only on whether it has a corresponding method, and does not care whether it is a certain type of object, such as JavaScript, Python.

Static languages: compared with dynamic languages, the data types of variables are determined at compile time (the data types must be declared before variables are used), and whether the types are matched at compile time, such as C language, Java

03. The concept of reflection

Java reflection mechanism: in the process of running, for any class, all its properties and methods can be known; for any object, its properties and methods can be called; this function of dynamically obtaining class information and calling object methods is the Java reflection mechanism.

Since there is a word "negative" in reflection, let's first look at what is "positive".

In Java, to use a method in a class, the "forward" looks like this:

ArrayList list = new ArrayList (); / / instantiate list.add ("reflection"); / / execute method

So how to achieve reverse (reflection)?

Class clz = Class.forName ("java.util.ArrayList"); Method method_add = clz.getMethod ("add", Object.class); Constructor constructor = clz.getConstructor (); Object object = constructor.newInstance (); method_add.invoke (object, "reflection"); Method method_get = clz.getMethod ("get", int.class); System.out.println (method_get.invoke (object, 0))

The result of the execution of the two pieces of code is the same, but the "forward" code already knows what class to run (ArrayList) before it is compiled, while the second piece of code knows that the running class is java.util.ArrayList only when the code is running.

04. The role of reflection

At this point, some students may wonder: "what's the use of reflection? I already know that the class I want to use is ArrayList, can't I just new an object and execute the methods in it?"

Yes, of course! However, in many scenarios, you don't know which class to use before the code runs, or decide which class to use at run time.

For example, there is such a function: "call Ali Yun's face recognition API"; this is not easy, refer to the other party's API document, it can be realized quickly.

FaceRecognition (Object faceImg) {/ / call Aliyun's face recognition API}

A month after its launch, the leader said, "our company has begun to cooperate with Tencent Cloud. Let's change the interface for face recognition."

FaceRecognition (Object faceImg) {/ / call Tencent Cloud face recognition API}

After two months of online operation, the leader said, "change it back." ...

Of course, smart programmers will want to set a switch configuration and let the switch decide which piece of code logic to take. If the leader wants to become an Amazon cloud service one day, just keep writing if-else:

FaceRecognition (Object faceImg) {if ("AL" .equals (configStr)) {/ / call Aliyun's face recognition API} else if ("TX" .equals (configStr)) {/ / call Tencent Cloud's face recognition API} else if ("AM" .equals (configStr)) {/ / call Amazon Cloud's face recognition API}}

But there is a better way:

1. Define an interface:

Interface FaceRecognitionInterface () {faceRecognition (Object faceImg);}

two。 Multiple implementation classes:

Class ALFaceRecognition implements FaceRecognitionInterface {/ / implementation of calling Ali Cloud's face recognition API} class TXFaceRecognition implements FaceRecognitionInterface {/ / calling Tencent Cloud's face recognition API}

3. In the code that calls the face recognition function:

String configStr = "read configuration, Aliyun or Tencent Cloud"; FaceRecognitionInterface faceRe = Class.forName (configStr). NewInstance (); faceRe.faceRecognition (faceImg)

If the above example, you still think that doing if-else judgment in calling methods is not much different from using reflection implementation, but what if programmer A provides the interface, programmer B provides the implementation, and programmer C writes the client?

Recall the use of JDBC, such as creating a connection:

Public Connection getConnection () throws Exception {Connection conn = null; / / initialize driver class Class.forName ("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection ("jdbc:mysql://url", "root", "admin"); return conn;}

Where:

Programmer A provides the interface: Oracle (formerly Sun) provides the JDBC standard (interface).

Programmer B provides implementation: each database vendor provides an implementation for their own database.

Programmer C write client: we programmers knock code in Java to access the database.

Summarize the role of Java reflection: you can design a more general and flexible architecture, and many frameworks can load unused classes according to their configuration in order to ensure their versatility, which requires reflection. In addition:

Dynamic proxy: enhances the method without changing the target object method, such as using AOP to intercept certain methods to print logs, which requires reflection to execute the contents of the method.

Comments: use the reflection mechanism to obtain comments and perform the corresponding behavior.

05. With the use of reflection

We know that the source file of the Java runtime is the class file (bytecode), so to use reflection, you need to get the bytecode file object. In Java, there are three ways to get the bytecode file object:

Call the class attribute of a class: class name.class

Call the object's getClass () method: object .getClass ()

Use the forName () static method in the Class class: Class.forName (full path to the class), which is recommended

The java.lang.reflect class library provides support for reflection:

Field: you can read and modify the properties of an object using the get and set methods

Method: you can use the invoke () method to call a method in an object

Constructor: you can create new objects with newInstance ().

06. Advantages and disadvantages of reflection

Advantages: dynamically obtain the content of classes and objects at run time, which greatly improves the flexibility and expansibility of the system; to exaggerate, reflection is the soul of framework design.

Disadvantages: there will be some performance loss, JVM can not optimize this code; break the encapsulation of the class.

In short, in the usual development process, you may feel that you have not written reflection-related code, but in the various open source frameworks we use, reflection is everywhere.

At this point, the study of "what is the role of Java reflection" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report