search
HomeJavajavaTutorialWhat are the knowledge points about Java reflection mechanism?

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
    }
}

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());

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);
    }
}

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);
    }
}

How to get the value of a private variable

//暴力反射:获取任意访问权限修饰符的安全检查
name.setAccessible(true);

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
This article is reproduced at:亿速云. 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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment