search
HomeJavajavaTutorialLet you understand the JAVA reflection mechanism (summary sharing)

This article brings you relevant knowledge about java, which mainly introduces issues related to the reflection mechanism, including what reflection is, what reflection can do, reflection-related APIs, etc., I hope everyone has to help.

Recommended study: "java Learning Tutorial"

1. What is reflection?

A very important concept in Java development is the Java reflection mechanism, which is also one of the important features of Java.

The concept of reflection was first proposed by Smith in 1982. It mainly refers to the ability of a program to access, detect and modify its own state or behavior. Through reflection, private methods and private properties can be called. Some frameworks also use the principle of reflection.

Reflection (reflection) is regarded as the key to dynamic language. The reflection mechanism allows the program to obtain the internal information of any
class during execution with the help of the Reflection API, and can directly operate it Internal properties and methods of any object.

A class has multiple components, such as member variables, methods, constructors, etc. Reflection is to load the class and dissect the various components of the class.

2. What can reflection do?

Java's reflection mechanism knows the basic structure of the class. This ability to detect the structure of the Java class is called the "self-examination" of the Java class. For example, in eclipse, with one click, the compilation tool will automatically list all the methods and properties that can be used by the object for the user to choose. This uses the principle of Java reflection to detect and self-examine the objects we create.

Reflection can do:

  • Determine the class to which any object belongs at run time;
  • Construct an object of any class at run time;
  • Determine the member variables and methods of any class at run time;
  • Obtain generic information at run time;
  • Call the member variables and methods of any object at run time ;
  • Annotations are processed at runtime;
  • Generate dynamic proxy;
  • ##java .lang.Class:Source of reflection
  • ##java.lang.reflect.Method
  • :Method
  • java.lang.reflect.Field
  • : Attribute
  • java.lang.reflect.Constructor
  • : Constructor
  • 4. Understanding of Class class

(1) Introduction:

After the program passes the javac.exe command, it will generate one or more bytecode files (ending with .class). Then we use the java.exe command to interpret and run a certain bytecode file. Equivalent to loading a certain bytecode file into memory. This process is called

class loading

. A class loaded into memory is called a runtime class, and this runtime class is used as an instance of Class. In other words, an instance of Class corresponds to a runtime class.

The runtime classes loaded into memory will be cached for a certain period of time. Within this time, we can obtain this runtime class in different ways

.


(2). Class loading process:

Loading: In our new object or use

Class.forName("Package name. Class")

When the class loader (ClassLoader) will load the class into memory and create a Class object

How to get the Class object?


    Class.
  • class

  • Object .
  • getClass()

  • ##Class.forName
  • ("Package name.Class");

Link:

Unload:

Unload from memory ( We don’t need to care about when to uninstall, it will be done by the JVM)

(3) Class loader

Class (CLASS) can only run after it is loaded into the JVM . When running the specified program, the JVM will load the compiled .class file into memory according to requirements and certain rules, and organize it into a complete Java application. This loading process is completed by the class loader, specifically, it is implemented by ClassLoader and its subclasses. The class loader itself is also a class. Its essence is to read the class file from the hard disk into the memory!

Classification of class loaders:

  1. BootStrap: is mainly responsible for loading the core class library (java.lang.*, etc.) and constructing ExtClassLoader and APPClassLoader;
  2. ExtClassLoader: Mainly responsible for loading some extended jar packages in the jre/lib/ext directory;
  3. AppClassLoader: Mainly responsible for Load the main function class of the application (the java file written by yourself is loaded by this class loader);
System.out.println("app:" + System.getProperty("java.class.path"));
System.out.println("ext:" + System.getProperty("java.ext.dirs"));
System.out.println("----bootstrap---");
String[] str = System.getProperty("sun.boot.class.path").split(";");

for (String s : str) {
    System.out.println(s);
}

Parental delegation (dispatch) mechanism:

When a file like Hello.class is to be loaded. Regardless of our custom class loader, we will first check whether it has been loaded in AppClassLoader. If so, there is no need to load it again. If not, the parent loader will be obtained, and then the loadClass method of the parent loader will be called. In the same way, the parent class will first check whether it has been loaded, and if not, go up. Pay attention to this recursive process. Until it reaches the Bootstrap classLoader, it is checking whether it has been loaded and will not choose to load it by itself. Until BootstrapClassLoader, there is no parent loader. At this time, I start to consider whether I can load it. If I can't load it, I will sink to the child loader to load it, all the way to the bottom layer. If no loader can load it, it will Throws ClassNotFoundException. So does anyone have the following questions?

Why should we design this mechanism?

One advantage of this design is that if someone wants to replace the system-level class: String.java. Tamper with its implementation. Under this mechanism, these system classes have been loaded by Bootstrap classLoader (why? Because when a class needs to be loaded, the first thing to try to load is BootstrapClassLoader), so other class loaders have not Loading again when the opportunity arises prevents the implantation of dangerous code to a certain extent.

Recommended study: "java tutorial"

The above is the detailed content of Let you understand the JAVA reflection mechanism (summary sharing). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
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