Home Java javaTutorial Detailed explanation of the principles of Java reflection implementation method

Detailed explanation of the principles of Java reflection implementation method

Oct 17, 2017 am 09:36 AM
java principle method

This article mainly introduces the implementation principle of Java method reflection in detail, which has certain reference value. Interested friends can refer to it

The blogger said: The Java reflection mechanism is that in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties; this dynamic acquisition of information and dynamic call of object methods The feature is called the reflection mechanism of the Java language. In this article, Zhan Xiaolang analyzes the implementation principle (source code) of the Java reflection mechanism. Interested students can spend a few minutes reading this article to understand.

Text

Detailed explanation of the principles of Java reflection implementation method

Method Reflection Example


public class ReflectCase {

  public static void main(String[] args) throws Exception {
    Proxy target = new Proxy();
    Method method = Proxy.class.Detailed explanation of the principles of Java reflection implementation method("run");
    method.Detailed explanation of the principles of Java reflection implementation method(target);
  }

  static class Proxy {
    public void run() {
      System.out.println("run");
    }
  }
}
Copy after login

Through Java The reflection mechanism can call any method of an object during runtime. If a large number of calls are made in this way, will there be any performance or memory risks? In order to fully understand the reflection mechanism of the method, we can only start from the underlying code!

Method Get

Call Detailed explanation of the principles of Java reflection implementation method of the Class class to obtain the method object Method with the specified method name and parameters.

Detailed explanation of the principles of Java reflection implementation method

Detailed explanation of the principles of Java reflection implementation method

The Detailed explanation of the principles of Java reflection implementation method method obtains the list of methods declared in the Class from the cache or Detailed explanation of the principles of Java reflection implementation method, and the Detailed explanation of the principles of Java reflection implementation method method will Detailed explanation of the principles of Java reflection implementation method Find a method object matching the name and parameters in the method list.

Detailed explanation of the principles of Java reflection implementation method

Detailed explanation of the principles of Java reflection implementation method

If a matching Method is found, make a new copy and Detailed explanation of the principles of Java reflection implementation method it, that is, Method.copy( )method.

Detailed explanation of the principles of Java reflection implementation method

The Method object Detailed explanation of the principles of Java reflection implementation methoded each time the Detailed explanation of the principles of Java reflection implementation method method is called is actually a new object, and the root attribute of the new object points to the original Method object. If needed frequently When calling, it is best to cache the Method object.

Detailed explanation of the principles of Java reflection implementation method

Get the list of methods declared in the Class from the cache or Detailed explanation of the principles of Java reflection implementation method. The implementation is as follows:

Detailed explanation of the principles of Java reflection implementation method

The Detailed explanation of the principles of Java reflection implementation method() method is implemented as follows:

Detailed explanation of the principles of Java reflection implementation method

There is a more important data structure ReflectionData, which is used to cache the following attribute data of the class read from the Detailed explanation of the principles of Java reflection implementation method:

Detailed explanation of the principles of Java reflection implementation method

It can be seen from the Detailed explanation of the principles of Java reflection implementation method() method implementation that the Detailed explanation of the principles of Java reflection implementation method object is of SoftReference type, indicating that it may be recycled when memory is tight, but it can also be controlled through the -XX:SoftRefLRUPolicyMSPerMB parameter At the time of recycling, as long as GC occurs, it will be recycled. If Detailed explanation of the principles of Java reflection implementation method is recycled and the reflection method is executed, then such an object can only be re-created through the Detailed explanation of the principles of Java reflection implementation method method. The Detailed explanation of the principles of Java reflection implementation method method is implemented as follows:

Detailed explanation of the principles of Java reflection implementation method

Reset the Detailed explanation of the principles of Java reflection implementation method field through the unsafe.compareAndSwapObject method; in the Detailed explanation of the principles of Java reflection implementation method method, if the ReflectionData object obtained through Detailed explanation of the principles of Java reflection implementation method() is not empty, try to obtain the declaredMethods property from the ReflectionData object. If it is the Once, or after being recycled by GC, if the reinitialized class attribute is empty, you need to obtain it from the Detailed explanation of the principles of Java reflection implementation method again and assign it to ReflectionData. The cached data can be used next time it is called.

Method calls

After obtaining the specified method object Method, you can call its Detailed explanation of the principles of Java reflection implementation method method. The Detailed explanation of the principles of Java reflection implementation method implementation is as follows:

Detailed explanation of the principles of Java reflection implementation method

It should be noted that the Detailed explanation of the principles of Java reflection implementation method object here is the key to the implementation of the Detailed explanation of the principles of Java reflection implementation method method. At first, the methodAccessor is empty, and acquireDetailed explanation of the principles of Java reflection implementation method needs to be called to generate a new Detailed explanation of the principles of Java reflection implementation method object. Detailed explanation of the principles of Java reflection implementation method itself is an interface, and the implementation is as follows:

Detailed explanation of the principles of Java reflection implementation method

In the acquireDetailed explanation of the principles of Java reflection implementation method method, an object that implements the Detailed explanation of the principles of Java reflection implementation method interface will be created through newDetailed explanation of the principles of Java reflection implementation method of the ReflectionFactory class. The implementation is as follows:

newDetailed explanation of the principles of Java reflection implementation method

In the ReflectionFactory class, there are two important fields: noInflation (default false) and inflationThreshold (default 15). In the checkInitted method, you can pass -Dsun.reflect.inflationThreshold=xxx and -Dsun.reflect.noInflation=true Reset these two fields and only set them once; if noInflation is false, the method newDetailed explanation of the principles of Java reflection implementation method will Detailed explanation of the principles of Java reflection implementation method the DelegatingDetailed explanation of the principles of Java reflection implementation methodImpl object. The class implementation of DelegatingDetailed explanation of the principles of Java reflection implementation methodImpl:

DelegatingDetailed explanation of the principles of Java reflection implementation methodImpl

In fact, the DelegatingDetailed explanation of the principles of Java reflection implementation methodImpl object It is a proxy object that is responsible for calling the Detailed explanation of the principles of Java reflection implementation method method of the delegate of the delegated object. The delegate parameter is currently a NativeDetailed explanation of the principles of Java reflection implementation methodImpl object, so the final method's Detailed explanation of the principles of Java reflection implementation method method calls the NativeDetailed explanation of the principles of Java reflection implementation methodImpl object's Detailed explanation of the principles of Java reflection implementation method method. The implementation is as follows:

The inflationThreshold in the ReflectionFactory class is used here. After the delegate calls the Detailed explanation of the principles of Java reflection implementation method method 15 times, if the call continues, the Detailed explanation of the principles of Java reflection implementation methodImpl object will be generated through the generateMethod method of the Detailed explanation of the principles of Java reflection implementation methodGenerator class and set as the delegate object, so that the Method will be executed next time. When Detailed explanation of the principles of Java reflection implementation methodd, the Detailed explanation of the principles of Java reflection implementation method() method of the newly created Detailed explanation of the principles of Java reflection implementation method object is called. What needs to be noted here is that when the generateMethod method generates a Detailed explanation of the principles of Java reflection implementation methodImpl object, it will generate the corresponding bytecode in the memory and call ClassDefiner.defineClass to create the corresponding Class object. The implementation is as follows:

Detailed explanation of the principles of Java reflection implementation method

In the implementation of the ClassDefiner.defineClass method, a Detailed explanation of the principles of Java reflection implementation method class loader object is generated every time it is called:

Detailed explanation of the principles of Java reflection implementation method

A new class loader is generated every time. , for performance reasons, these generated classes can be unloaded in some cases, because the unloading of classes will only be recycled when the class loader can be recycled. If the original class loader is used, then This may cause these newly created classes to never be unloaded. From the design point of view, we do not want these classes to always exist in the memory. Just have them when needed!

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

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

See all articles