Introduction to analysis of Java reflection
This document describes the analysis and introduction of Java reflection
1. What is reflection?
From Baidu Encyclopedia, we can know that Java reflection is in the running state. For any class, we can know all the properties and methods of this class; for any object, we can call any of its methods and properties; and can change its properties. And this is why Java is considered dynamic (or quasi-dynamic, why is it said to be quasi-dynamic, because the general definition of a dynamic language is that when the program is running, it allows the program structure or variable type to be changed. This language is called a dynamic language. From this point of view, Perl, Python, and Ruby are dynamic languages, and C++, Java, and C# are not dynamic languages.) A key property of languages.
2. What can reflection do?
We know that the reflection mechanism allows the program to obtain the internal information of any class with a known name at runtime, including its modifiers (modifiers), fields (properties), methods (methods), etc., and can be changed at runtime. fields content or calling methods. Then we can write code more flexibly, and the code can be assembled at runtime without the need for source code linking between components, reducing the coupling of the code; there is also the implementation of dynamic agents, etc.; but we need to pay attention to the improper use of reflection. It will be very costly!
3. The specific implementation of reflection
The following is a basic class Person
package com.ys.reflex; public class Person { //私有属性 private String name = "Tom"; //公有属性 public int age = 18; //构造方法 public Person() { } //私有方法 private void say(){ System.out.println("private say()..."); } //公有方法 public void work(){ System.out.println("public work()..."); } }
①. Get the Class 3 This way
//1、通过对象调用 getClass() 方法来获取,通常应用在:比如你传过来一个 Object // 类型的对象,而我不知道你具体是什么类,用这种方法 Person p1 = new Person(); Class c1 = p1.getClass(); //2、直接通过 类名.class 的方式得到,该方法最为安全可靠,程序性能更高 // 这说明任何一个类都有一个隐含的静态成员变量 class Class c2 = Person.class; //3、通过 Class 对象的 forName() 静态方法来获取,用的最多, // 但可能抛出 ClassNotFoundException 异常 Class c3 = Class.forName("com.ys.reflex.Person");
It should be noted that:A class will only have one Class instance in the JVM,That is, we will perform the above-obtained c1, c2, c3 equals comparison, found to be true
②,Get member variables, member methods, interfaces, super classes, constructors, etc. through the Class class
Check the API and you can see that Class has many methods:
GetName(): Get the complete name of the class.
GetFields(): Get the public type attributes of the class.
getDeclaredFields(): Get all attributes of the class. Including private declared and inherited classes
GetMethods(): Get the public type method of the class.
getDeclaredMethods(): Get all methods of the class. Including private declared and inherited classes
GetMethod(String name, Class[] parameterTypes): Get the specific method of the class, the name parameter specifies the name of the method, and the parameterTypes parameter specifies the parameter type of the method.
GetConstructors(): Get the public type constructor of the class.
getConstructor(Class[] parameterTypes): Get the specific constructor method of the class. The parameterTypes parameter specifies the parameter type of the constructor method.
newInstance(): Create an object of this class through the constructor method of the class without parameters.
We use an example to comprehensively demonstrate the above method:
//获得类完整的名字 String className = c2.getName(); System.out.println(className);//输出com.ys.reflex.Person //获得类的public类型的属性。 Field[] fields = c2.getFields(); for(Field field : fields){ System.out.println(field.getName());//age } //获得类的所有属性。包括私有的和继承类的 Field [] allFields = c2.getDeclaredFields(); for(Field field : allFields){ System.out.println(field.getName());//name age } //获得类的public类型的方法。这里包括 Object 类的一些方法 Method [] methods = c2.getMethods(); for(Method method : methods){ System.out.println(method.getName());//work waid equls toString hashCode等 } //获得类的所有方法。 Method [] allMethods = c2.getDeclaredMethods(); for(Method method : allMethods){ System.out.println(method.getName());//work say } //获得指定的属性 Field f1 = c2.getField("age"); System.out.println(f1); //获得指定的私有属性 Field f2 = c2.getDeclaredField("name"); //启用和禁用访问安全检查的开关,值为 true,则表示反射的对象在使用时应该取消 java 语言的访问检查;反之不取消 f2.setAccessible(true); System.out.println(f2); //创建这个类的一个对象 Object p2 = c2.newInstance(); //将 p2 对象的 f2 属性赋值为 Bob,f2 属性即为 私有属性 name f2.set(p2,"Bob"); //使用反射机制可以打破封装性,导致了java对象的属性不安全。 System.out.println(f2.get(p2)); //Bob //获取构造方法 Constructor [] constructors = c2.getConstructors(); for(Constructor constructor : constructors){ System.out.println(constructor.toString());//public com.ys.reflex.Person() }
4. Reflection summary
Flexible use of reflection can make our code more flexible, here is an example of JDBC native code registration Drivers, hibernate's entity classes, Spring's AOP, etc. all have reflection implementations. But everything has two sides. Reflection will also increase the performance and complexity of the system. Reasonable use is the truth!
The above is the detailed content of Introduction to analysis of Java reflection. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Java reflection is a powerful tool that allows you to access the private fields and methods of a class, thereby revealing the inner workings of the software. This is useful in areas such as reverse engineering, software analysis and debugging. To use Java reflection, you first need to import the java.lang.reflect package. Then, you can use the Class.forName() method to obtain the Class object of a class. Once you have a Class object, you can use various methods to access the fields and methods of the class. For example, you can use the getDeclaredFields() method to get all fields of a class, including private fields. You can also use the getDeclaredMethods() method

Obtaining method: 1. Create a sample object; 2. Obtain the value of the field through field.get(person), where person is the sample object and field is the Field object, representing a field; 3. Set the field through setAccessible(true) In the accessible state, even private fields can get their values; 4. Traverse the field array, get the name and corresponding value of each field, and print it out.

The principle of the Java reflection mechanism is that when a bytecode file is loaded into memory, the jvm will dissect the bytecode and create a Class object of the object. The jvm stores all the bytecode file information into the Class object. As long as After obtaining the Class object, you can use the object to set the properties or methods of the object, etc. The reflection mechanism is the function of knowing all the attributes and methods of any class in the running state. For any object, it can call any of its attributes and methods, dynamically obtain information, and dynamically call object methods.

The steps to create an object through the Java reflection mechanism are as follows: Load the target class: Use the Class.forName() method. Get the constructor: use the getDeclaredConstructor() method. Create an object: Use the newInstance() method to pass parameters.

In-depth understanding of the principles and applications of Java reflection mechanism 1. The concept and principle of reflection mechanism Reflection mechanism refers to the ability to dynamically obtain class information, access and operate class members (properties, methods, constructors, etc.) while the program is running. Through the reflection mechanism, we can dynamically create objects, call methods and access properties while the program is running, without knowing the specific information of the class at compile time. The core of the reflection mechanism is the classes and interfaces in the java.lang.reflect package. Among them, the Class class represents the bytes of a class

Obtaining method: 1. Create a Person class and obtain the Class object of the class through reflection; 2. Use the getDeclaredFields method to obtain all fields of the class; 3. By traversing the field array, set the fields to an accessible state, and then use get The method gets the value of the field and prints the field name and value.

The NoSuchFieldException exception in Java refers to the exception thrown when trying to access a non-existent field (Field) during reflection. In Java, reflection allows us to manipulate classes, methods, variables, etc. in the program through code, making the program more flexible and scalable. However, when using reflection, if the accessed field does not exist, a NoSuchFieldException will be thrown. NoSuchFieldException

The java reflection calling methods are: 1. Class class; 2. Constructor class; 3. Method class; 4. Field class; 5. ClassLoader class. Detailed introduction: 1. Class class, used to obtain class information, including class name, member variables and methods, etc. You can create an instance of the class through the "newInstance()" method of Class class; 2. Constructor class, used to obtain Constructor parameter types, modifiers, return types and other information, etc.
