Home > Java > javaTutorial > What are the knowledge points about Java reflection mechanism?

What are the knowledge points about Java reflection mechanism?

王林
Release: 2023-05-21 12:34:20
forward
1031 people have browsed it

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!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template