Table of Contents
Class declaration cycle
Home Java javaTutorial What are the knowledge points about Java reflection mechanism?

What are the knowledge points about Java reflection mechanism?

May 21, 2023 pm 12:34 PM
java

Class declaration cycle

java source code----->javac-------------->java bytecode file----- --------->java----------------->Class object (memory space: metaspace, local memory)------ ------------------new--------->Instantiated object----------------- -gc------------->Unload object

What are the knowledge points about Java reflection mechanism?

##Class objects can be obtained at different stages

  • Object.getClass() (memory stage)

  • Test.class (metaspace)

  • class.forName("Class full Name: Package name, class name"): You can get the object without entering the memory space (hard disk)

For example, when we use jdbc to operate the database, enter in this class Before memory, we can use the full name of the class - package name class name, call the class and use

What are the knowledge points about Java reflection mechanism?

to get the Class class object scenario

  • Class.forName("Full name of the class"): mostly used in configuration files, define the class name in the configuration file, read the configuration file, and load the class

  • Class name.class: mostly used for passing parameters

  • Object name.getClass(): mostly used for object acquisition of class objects

Summary : A file loaded by the same class loader will only be loaded once during a program run. No matter which method is used, the class object obtained is the same

Code example:

package com.reflect;
public class TestReflectPerson {
    public static void main(String[] args) throws ClassNotFoundException {
        //1.class.forName()
        Class class1=Class.forName("com.reflect.Person");
        System.out.println(class1);
        //2.类名.class
        Class class2=Person.class;
        System.out.println(class2);
        //2.对象名.getClass()
        Class class3=new Person().getClass();
        System.out.println(class3);
        System.out.println(class1==class2);  //true
        System.out.println(class2==class3);  //true
    }
}
Copy after login

Function of class object

Get member variables: Get all: class object.getDeclaredFields(), get one: class object.getDeclaredField()

  • Set value set (Object obj,Object value)

  • Get the value get(Object obj)

Get any permission-modified member variable to get the setting value, required Use setAccessible(true)-----violent reflection

Member method: class object.getDeclaredMethods()

Execution method invoke(Object object,Object… agrs) (the number of parameters is arbitrary, Optional)

Get the method name getName()

Construction method: Class object.getDeclaredConstructors()

Although you must have a parameterless constructor, use newInstance( ) method can omit the steps of obtaining the constructor and obtaining the object

This method requires the actual construction method to assign actual parameters

//获得构造方法对象,
        Constructor cons1 = pcla.getDeclaredConstructor(String.class, int.class);
        Person p2 = (Person)cons1.newInstance("李四",19);
        System.out.println("p2:"+p2.getName());
Copy after login

newInstance() If you create a parameterless constructor to create an object, you can Use class objects to create objects, skip getting the constructor object

Get

Get the name of the class: getName() Print out the full name: class name package name

only Want to print a separate class name: getSimpleName()

Get the member variable name of the class

What are the knowledge points about Java reflection mechanism?

Properties file: The content is connected with an equal sign, such as k=v,

What are the knowledge points about Java reflection mechanism?

Code example:

package com.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class TestReflectPerson {
    public static void main(String[] args) throws Exception {
       /* //1.class.forName()
        Class class1=Class.forName("com.reflect.Person");
        System.out.println(class1);
        //2.类名.class
        Class class2=Person.class;
        System.out.println(class2);
        //2.类名.getClass()
        Class class3=new Person().getClass();
        System.out.println(class3);
        System.out.println(class1==class2);
        System.out.println(class2==class3);*/
        //获取对象
        Class tclass=Class.forName("com.reflect.Person");
        //通过类对象获取成员变量们
        Field[] fields = tclass.getDeclaredFields();
        System.out.println("获取Person对象的所有属性对象");
        for (Field field:fields){
           System.out.println(field);
       }
        //指定获取Person对象的属性对象
        System.out.println("指定获取Person对象的属性对象");
        Field age=tclass.getDeclaredField("age");
        System.out.println("age:"+age);
        //通过类对象获取所有的构造方法
        Constructor[] constructors = tclass.getDeclaredConstructors();
        System.out.println("获取Person的所有构造方法对象");
        for (Constructor constructor:constructors){
            System.out.println(constructor);
        }
        //通过类对象获取无参的构造方法
        Constructor constructor = tclass.getDeclaredConstructor();
        System.out.println("constructor:"+constructor);
        //通过类对象获取有参的构造方法
        Constructor constructor1 = tclass.getDeclaredConstructor(String.class,int.class);
        System.out.println("constructor1:"+constructor1);
        //通过类对象获取所有的成员方法
        Method[] methods = tclass.getDeclaredMethods();
        for (Method method:methods){
            System.out.println("method:"+method);
        }
        //通过类对象获取getAge成员方法
        Method getAge = tclass.getDeclaredMethod("getAge");
        System.out.println("getAge:"+getAge);
        //通过类对象获取getAge成员方法
        Method setAge = tclass.getDeclaredMethod("setAge", int.class);
        System.out.println("setAge:"+setAge);
    }
}
Copy after login

Get member variable code example:

package com.reflect;
import java.lang.reflect.Field;
public class TestField {
    public static void main(String[] args) throws Exception {
        Class pcla=Person.class;
        /*//获取公共访问权限的成员变量
        Field[] fields = pcla.getFields();
        for (Field field:fields){
            System.out.println("getFild:"+field);
        }
        System.out.println();
        //获取所有访问权限的成员变量
        Field[] fielddes = pcla.getDeclaredFields();
        for (Field field:fielddes){
            System.out.println("field:"+field);
        }*/
        Field name = pcla.getDeclaredField("name");
        System.out.println(name);
        Person person=new Person();
        //暴力反射:获取任意访问权限修饰符的安全检查
        name.setAccessible(true);
        //获取公共成员变量的值
        Object value = name.get(person);
        System.out.println(value);
        //获取任意访问权限的成员变量的值
        Object value2 = name.get(person);
        System.out.println("value2:"+value2);
        //设置任意访问权限的成员变量的值
        name.set(person,"张三");
        Object value3=name.get(person);
        System.out.println("name:"+value3);
    }
}
Copy after login

How to get the value of a private variable

//暴力反射:获取任意访问权限修饰符的安全检查
name.setAccessible(true);
Copy after login
Judge processes and threads based on whether there is a main method

Process: It has its own main method and can be started by relying on its own main method. It is called a process

Thread: It does not have its own main method and needs to rely on Other tools to run

For example: servlet needs to be run with the help of tomcate. Tomcate has its own main method

The background of reflection (remember)

For example: in When the servlet is run with the help of the tool tomcate, tomacate cannot access the resources of the class when running the project, which results in reflection

Why tomcate cannot get the new object

Detailed explanation: tomcate is impossible Called through new, because tomacate is generated and written first, and the class is written later, so tomcate does not know what the object of new is. You can obtain the file path through package scanning, but you cannot use new in this way. way, resulting in reflection.

ate has its own main method

The background of reflection

Example: When the servlet is run by using the tool tomacate, tomacate cannot access the class when running the project resources, resulting in reflection

Why can’t tomcate get the new object?

Detailed explanation: Tomcate cannot be called through new, because tomacate is generated and written first, and the class is written later, so tomcate does not know what the object of new is. It can be called through package scanning. to obtain the file path, but this method cannot use new, which results in reflection.

When tomcate wants to call the doGet and doPost methods, because these two methods are not static, they must be called through the new object, but tomcate cannot create objects, so reflection is generated to obtain the file

The above is the detailed content of What are the knowledge points about Java reflection mechanism?. 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

Video Face Swap

Video Face Swap

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

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)

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

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

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

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles