search
HomeJavajavaTutorialDetailed explanation of reflection mechanism in Java

Detailed explanation of reflection mechanism in Java

Oct 16, 2017 am 10:19 AM
javareflectionDetailed explanation

This article mainly introduces relevant information about the detailed explanation of examples of Java reflection mechanism. I hope this article can help everyone understand and master the reflection mechanism. Friends in need can refer to

Java Detailed explanation of examples of reflection mechanism

Preface

Today I will introduce the reflection mechanism of Java. In the past, we used new to obtain an instance of a class. Example comes out. That's too low. Come with me today to learn a more advanced way to achieve it.

Text

Java reflection mechanism definition

The Java reflection mechanism means that in the running state, for any class, it can know All properties and methods of this class; for any object, any of its methods and properties can be called; this function of dynamically obtaining information and dynamically calling the object's methods is called the reflection mechanism of the Java language. To sum up in one sentence, reflection can realize the properties and methods of any class at runtime.

Advantages and Disadvantages of Reflection Mechanism

Why use reflection mechanism? Isn't it enough to create objects directly? This involves the concepts of dynamic and static

Static compilation: Determine the type at compile time and bind the object, that is, pass.

Dynamic compilation: Determine the type and bind the object at runtime. Dynamic compilation maximizes the flexibility of Java, embodies polymorphic applications, and reduces the coupling between classes.

Advantages

It can realize dynamic creation of objects and compilation, which reflects great flexibility, especially in the development of J2EE. The performance is very obvious. For example, for a large-scale software, it is impossible to design it perfectly in one go. After the program is compiled and released, when it is found that certain functions need to be updated, we cannot ask the user to uninstall the previous one and then reinstall it. The new version, if this is the case, this software will definitely not be used by many people. If it is static, the entire program needs to be recompiled once to realize the function update. If it uses the reflection mechanism, it does not need to be uninstalled. It only needs to be dynamically created and compiled at runtime to realize the function.

Disadvantages

Has an impact on performance. Using reflection is basically an interpreted operation where we can tell the JVM what we want to do and it meets our requirements. Such operations are always slower than just performing the same operation directly.

Understanding the Class class and class type

If you want to understand reflection, first understand the Class class, which is the basis for reflection implementation.

A class is an instance object of the java.lang.Class class, and Class is a class of all classes (There is a class named Class). For ordinary objects, we generally create and represent them like this:


Code code1 = new Code();

As mentioned above, all classes are objects of Class, so how to express it? Can it be expressed in the following way:


Class c = new Class();

But when we look at the source code of Class, it is written like this:


private Class(ClassLoader loader) { 
classLoader = loader; 
}

You can see that the constructor is private, and only the JVM can create Class Object, so we cannot create a new Class object like a normal class. Although we cannot create a new Class object, we can get a Class object through an existing class. There are three ways, as follows:


Class c1 = Code.class;

This shows that any class has an implicit static member variable class, which is obtained by obtaining the static member variable class of the class


Class c2 = code1.getClass();

code1 is an object of Code, which is obtained through the getClass() method of a class object


Class c3 = Class.forName(“com.trigl.reflect.Code”);

This The first method is that the Class class calls the forName method, which is obtained through the fully qualified name of a class. Here, c1, c2, and c3 are all objects of Class. They are exactly the same, and they have a scientific name called Code's class type. ). This is strange. Didn't we say that Code is an object of Class, and c1, c2, and c3 are also objects of Class, so aren't Code the same as c1, c2, and c3? Why is it still called Code and what type of class? Don’t get hung up on whether they are the same here, just understand what the class type does. As the name suggests, the class type is the type of the class, that is, it describes what a class is and what it contains, so we can know a class through the class type. properties and methods, and can call the properties and methods of a class. This is the basis of reflection.

Give a simple example code:


public class ReflectDemo { 
public static void main(String[] args) throws ClassNotFoundException { 
//第一种:Class c1 = Code.class; 
Class class1=ReflectDemo.class; 
System.out.println(class1.getName());

  //第二种:Class c2 = code1.getClass();
  ReflectDemo demo2= new ReflectDemo();
  Class c2 = demo2.getClass();
  System.out.println(c2.getName());

  //第三种:Class c3 = Class.forName("com.trigl.reflect.Code");
  Class class3 = Class.forName("com.tengj.reflect.ReflectDemo");
  System.out.println(class3.getName());
}
}

Execution result:


com.tengj.reflect.ReflectDemo 
com.tengj.reflect.ReflectDemo 
com.tengj.reflect.ReflectDemo

Java reflection related operations

We knew how to get Class earlier, so what can we do with this Class?

The summary is as follows:

Get the member method Method
Get the member variable Field
Get the constructor Constructor

Let’s introduce it in detail

Get member method information

Getting a certain method individually is obtained through the following method of the Class class:


public Method getDeclaredMethod(String name, Class c){

}

The above is the detailed content of Detailed explanation of reflection mechanism in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor