Home Java javaTutorial What is Java reflection mechanism? How to use Java reflection mechanism

What is Java reflection mechanism? How to use Java reflection mechanism

Sep 20, 2018 pm 02:55 PM
java reflection mechanism

This article brings you what is the Java reflection mechanism? The method of using Java reflection mechanism has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Speaking of the reflection mechanism, people who come into contact with it for the first time may be confused. Reflection? What reflection? How to reflect? What is reflection for? Next, I will talk about Java's reflection machine in this article

But before that, there is still a problem that needs to be solved. The dynamics in the title name. Speaking of dynamics, Let me first introduce dynamic language and static language

##static language

 Static language is Languages ​​in which the data type of the variable can be determined at compile time. Most statically typed languages ​​require that the data type must be declared before using the variable. For example: C, Java, Delphi, C#, etc.

Dynamic language

 Dynamic language is a language that determines the data type at runtime. There is no need for a type declaration before a variable is used. Usually the type of the variable is the type of the value to which it is assigned. For example, PHP/ASP/Ruby/Python/Perl/ABAP/SQL/JavaScript/Unix Shell, etc. andDynamic language means that the program can change its structure while it is running: new functions can be introduced, existing functions can be deleted and other structural changes.

At this time, you may have questions. Since Java is a static language, how can it be dynamic? One is that Java has a mechanism related to dynamics: Reflection mechanism. Through the reflection mechanism, Java can load, detect and use classes that are completely unknown during compilation when the program is running, and can generate related class object instances, so that its methods can be called or a certain attribute value can be changed. So JAVA can also be regarded as a semi-dynamic language

Let’s talk about the reflection mechanism

 Reflection mechanism concept The reflection mechanism in Java means that in the running state, any class can know all the properties and methods of this class; And for any object, any of its methods can be called; this function of dynamically obtaining information and dynamically calling object methods is called the reflection mechanism of the Java language.

  The principle of reflection lies in the Class object

Take a look at the process of program loading

You can probably see from the picture what reflection is used for, then let’s talk about other aspects of reflection

 

Reflection API

  The reflection API is used to generate information about classes, interfaces or objects in the JVM.

  -
Class: The core class of reflection, which can obtain the attributes, methods and other information of the class.   -
Field class: A class in the Java.lang.reflec package, which represents the member variables of the class and can be used to get and set attribute values ​​in the class.   -
Method class: The class in the Java.lang.reflec package represents the method of the class. It can be used to obtain method information or execute methods in the class.   -
Constructor class: Class in the Java.lang.reflec package, representing the construction method of the class.

Let’s talk about how to use reflection  

1. Steps

  • Get the Class object of the class you want to operate

  • Call the method in the Class class

  • Use Reflection API to operate this information

2. Method to obtain Class object

//假设我们有一个Student类
方法一、(推荐)
    Class clas = Class.forName("first.Student");//“”里写的是类的全路径

方法二、
    Student stu = new Student();
    Class clas = stu.getClass();

方法三、
    Class clas = Student.Class;
Copy after login

You can try using two different methods to obtain clas1 and clas2, and then System.ou.println(clas1==clas2) to see what will be output. The reason is in the picture

3. Get the constructor method, Field, main method and call

Student.java

public class Student {
    public String name;
    protected int age;
    char sex;
    private String phoneNum;
    
    public static void main(String[] args) {

        System.out.println("main方法执行了。。。");

    }
    //---------------构造方法-------------------
    Student(String str) {
        System.out.println("(默认)的构造方法 s = " + str);
    }

    // 无参构造方法
    public Student() {
        System.out.println("调用了公有、无参构造方法执行了。。。");
    }

    // 有一个参数的构造方法
    public Student(char name) {

        System.out.println("姓名:" + name);
    }

    // 有多个参数的构造方法
    public Student(String name, int age) {
        this.name=name;this.age=age;
        System.out.println("姓名:" + name + "年龄:" + age);// 这的执行效率有问题,以后解决。
    }

    // 受保护的构造方法
    protected Student(boolean n) {
        System.out.println("受保护的构造方法 n = " + n);
    }

    // 私有构造方法
    private Student(int age) {
        System.out.println("私有的构造方法   年龄:" + age);
    }
    
    public String toString() {
        return "Student [name=" + name + ", age=" + age + ", sex=" + sex
                + ", phoneNum=" + phoneNum + "]";
    }
}
Copy after login

Constructors.java(构造方法)

package first;

import java.lang.reflect.Constructor;

public class Constructors {
    public static void main(String[] args) throws Exception {
        
        Class clas=Class.forName("first.Student");
        
        System.out.println("所有公有构造方法");
        Constructor[] conArry=clas.getConstructors();
        for(int i=0;i<conArry.length;i++) {
            System.out.println(conArry[i]);
        }
        
        System.out.println("所有的构造方法");
        conArry=clas.getDeclaredConstructors();
        for(int i=0;i<conArry.length;i++) {
            System.out.println(conArry[i]);
        }
        
        System.out.println("获取公有无参的构造方法");
        Constructor con=clas.getConstructor(null);
        System.out.println("con="+con);
        Object obj=con.newInstance();
        
        System.out.println("获取私有构造方法,并调用");
        con=clas.getDeclaredConstructor(char.class);
        System.out.println(con);
        //con.setAccessible(true);//暴力访问,针对private方法和字段时使用
        obj=con.newInstance(&#39;a&#39;);//创建对象
    }
}
Copy after login

输出

所有公有构造方法
public first.Student(char)
public first.Student()
public first.Student(java.lang.String,int)
所有的构造方法
protected first.Student(boolean)
private first.Student(int)
public first.Student(char)
public first.Student()
first.Student(java.lang.String)
public first.Student(java.lang.String,int)
获取公有无参的构造方法
con=public first.Student()
调用了公有、无参构造方法执行了。。。
获取私有构造方法,并调用
public first.Student(char)
姓名:a
Copy after login

Fields.java(字段)

package first;
import java.lang.reflect.Field;
public class Fields {
    public static void main(String[] args)throws Exception {
        // TODO Auto-generated method stub
        Class StuClass=Class.forName("first.Student");
        
        System.out.println("获取所有公有的字段");
        Field[] fieldArry=StuClass.getFields();
        for(Field f:fieldArry) {
            System.out.println(f);
        }
        System.out.println("获取所有的字段(包括私有、受保护、默认的)");
        fieldArry=StuClass.getDeclaredFields();
        for(Field f:fieldArry) {
            System.out.println(f);
        }
        System.out.println("获取公有字段并调用");
        Field f = StuClass.getField("name");
        System.out.println(f);
        Object obj=StuClass.getConstructor().newInstance();
        StuClass.getConstructor(String.class,int.class).newInstance("a",10);
        f.set(obj, "b");
        Student stu=(Student)obj;
        System.out.println(stu.name);
        
        System.out.println("获取私有字段并调用");
        f = StuClass.getDeclaredField("phoneNum");
        System.out.println(f);
        f.setAccessible(true);//暴力反射,解除私有限定
        f.set(obj, "18888889999");
        System.out.println("验证电话:" + stu);
    }
}
Copy after login

输出

获取所有公有的字段
public java.lang.String first.Student.name
获取所有的字段(包括私有、受保护、默认的)
public java.lang.String first.Student.name
protected int first.Student.age
char first.Student.sex
private java.lang.String first.Student.phoneNum
获取公有字段并调用
public java.lang.String first.Student.name
调用了公有、无参构造方法执行了。。。
姓名:a年龄:10
b
获取私有字段并调用
private java.lang.String first.Student.phoneNum
验证电话:Student [name=b, age=0, sex=
Copy after login

Main.java

package first;
import java.lang.reflect.Method;
public class Main {
    public static void main(String[] args) {
        try {
            // 1、获取Student对象的字节码
            Class clazz = Class.forName("first.Student");

            // 2、获取main方法

            Method methodMain = clazz.getMethod("main", String[].class);// 第一个参数:方法名称,第二个参数:方法形参的类型,

            // 3、调用main方法
            // methodMain.invoke(null, new String[]{"a","b","c"});
            // 第一个参数,对象类型,因为方法是static静态的,所以为null可以,第二个参数是String数组
            // 这里拆的时候将 new String[]{"a","b","c"} 拆成3个对象。。。所以需要将它强转。
            methodMain.invoke(null, (Object) new String[] {});// 方式一
            // methodMain.invoke(null, new Object[]{new String[]{"a","b","c"}});//方式二
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Copy after login

The above is the detailed content of What is Java reflection mechanism? How to use 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)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

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

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 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 to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

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

See all articles