search
HomeJavajavaTutorialDetailed explanation of examples of reflection mechanism in Java

This article mainly introduces relevant information about Java reflection mechanism examples. Here is a detailed analysis of the reflection mechanism in Java. Friends in need can refer to

Java Reflection Mechanism Detailed Examples.

1. Is JAVA a dynamic language?

Generally speaking, when it comes to dynamic languages, it means that the program structure or variable type is allowed to be changed while the program is running. From this point of view, Java, like C++, is not a dynamic language.

But JAVA has a very prominent dynamic related mechanism: reflection. Through reflection, Java can load, detect and use classes that were fully summed during compilation at runtime, generate their object entities, call their methods or set values ​​for properties. So Java is considered a semi-dynamic language.

The concept of reflection:

The reflection mechanism in Java means that in the running state, for any class, all properties and methods of this class can be known;

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

II , Dynamic properties

##2.1. Dynamic properties

Generate object instances during runtime;

Call methods during runtime;
Change attributes during runtime

2.2. Functions that can be achieved by the Java reflection mechanism

Judge the class to which any object belongs at runtime

Construct the class of any class at runtime Object
Judge the methods and attributes of any class at runtime
Call the method of any object at runtime
Generate a dynamic proxy

##2.3. Java reflection application scenarios

Many objects in Java programs will have two types at runtime: compile-time type and run-time type

The compile-time type is determined by the time when the object is declared. The type used is determined by the type used. The type at runtime is determined by the type actually assigned to the object.

For example:

Person p =new Student();

The compile-time type is Person, and the run-time type is Person. For Student

In addition, the program may also receive an object passed in from the outside during runtime. The compile-time type of the object is Object, but the program needs to call the method of the runtime type of the object. To solve these problems, programs need to discover real information about objects and classes at runtime. However, if it is impossible to predict which classes the object and class may belong to at compile time, and the program only relies on runtime information to discover the real information of the object and class, reflection must be used at this time

3. Java Reflection API

The reflection API is used to generate information about classes, interfaces or objects in the current JAVA virtual machine.

Class class: The core class of reflection, which can obtain the attributes, methods and other content information of the class.

Field class: Java.lang.reflect. Represents the attributes of the class, and can get and set the attribute values ​​​​of the class.

Method class:Java.lang.reflect. Represents a method of a class, which can be used to obtain information about methods in a class or execute methods
Construcor class: Java.lang.reflect. Represents the constructor method of the class.


4. Get all methods and properties

Person class

package com.pb.Reflect.classinfo;

public class Person {
  private String name;
  private String gender;
  private int age;

  private Person() {
  //
  }
  public Person(String name, String gender, int age) {
    super();
    this.name = name;
    this.gender = gender;
    this.age = age;
  }
  //getter、和setter方法
  private String getName() {
    return name;
  }
  private void setName(String name) {
    this.name = name;
  }
  public String getGender() {
    return gender;
  }
  public void setGender(String gender) {
    this.gender = gender;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }

  public String toString(){
    return "姓名:"+name+"年龄: "+age;
  }

}

Use reflection:

package com.pb.Reflect.classinfo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import javax.swing.JOptionPane;

/*
 * 通过用户输入类的全路径,来获取该类的成员方法和属性
 * Declared获取全部不管是私有和公有
 * 1.获取访问类的Class对象
 * 2.调用Class对象的方法返回访问类的方法和属性信息
 */
public class ReflectDemo {

  /*
   * 构造方法
   */
  public ReflectDemo(){
    //用户输入类的全路径径
    //使用String组件
    String classpsth=JOptionPane.showInputDialog(null,"输入类的全路径");
    //使用Class.forName方法根据输入的类的全路径 返回该类的Class对象
    try {
      Class cla = Class.forName(classpsth);
      //利用Class对象的cla的自审,返回方法对象集合
      Method [] method=cla.getDeclaredMethods(); //返回所有的方法
      System.out.println("========获取方法信息============");
      for (Method meth : method) {
        //遍历method数组,并输出方法信息
        System.out.println(meth.toString());
      }
      System.out.println("========获取出方法信息结束============");
      //获取属性利用Class对象的cla的自审,返回成员属性对象集合
       Field [] field=cla.getDeclaredFields();
        System.out.println("========获取成员属性信息============");
        for (Field f : field) {
          System.out.println(f.toString());
        }
        System.out.println("========获取成员属性信息结束============");
      //获取属性利用Class对象的cla的自审,返回构造方法集合
        Constructor [] constructor=cla.getDeclaredConstructors();
        System.out.println("========获取成员构造方法信息============");
        for (Constructor constru : constructor) {
          System.out.println(constru.toString());
        }
        System.out.println("========获取成员构造方法信息结束============");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
      System.out.println("路径输入错误!");
    }
  }

}

package com.pb.Reflect.classinfo;

public class TestReflection {

  public static void main(String[] args) {
    ReflectDemo rd=new ReflectDemo();

  }

}

Enter com.pb.Reflect.classinfo.Person

Result:

========获取方法信息============
public java.lang.String com.pb.Reflect.classinfo.Person.getGender()
public void com.pb.Reflect.classinfo.Person.setGender(java.lang.String)
public int com.pb.Reflect.classinfo.Person.getAge()
public void com.pb.Reflect.classinfo.Person.setAge(int)
public java.lang.String com.pb.Reflect.classinfo.Person.toString()
private java.lang.String com.pb.Reflect.classinfo.Person.getName()
private void com.pb.Reflect.classinfo.Person.setName(java.lang.String)
========获取出方法信息结束============
========获取成员属性信息============
private java.lang.String com.pb.Reflect.classinfo.Person.name
private java.lang.String com.pb.Reflect.classinfo.Person.gender
private int com.pb.Reflect.classinfo.Person.age
========获取成员属性信息结束============
========获取构造方法信息============
private com.pb.Reflect.classinfo.Person()
public com.pb.Reflect.classinfo.Person(java.lang.String,java.lang.String,int)
========获取构造方法信息结束============

5. Steps to use reflection

5.1. Steps

Java.lang.reflect

Get the Java.lang.Class object of the class you want to operate

Call the method of Class

Use the reflection API to operate this information

5.2. How to get the Class object

Call the getClass() method of an object


Person p = new Person();
Class cla=p.getClass();

Call the class attribute of a certain class to obtain the Class object corresponding to the class


Class cls=Person.class;

Use the forName() static method of the Class class


Class cla=Class.forName(“类的全路径”);

6. The second method is the getClass() method of the object

Person class. Because the object is to be declared, the constructor method public

package com.pb.Reflect.classinfo;

public class Person {
  private String name;
  private String gender;
  private int age;

  public Person() {
  //
  }
  public Person(String name, String gender, int age) {
    super();
    this.name = name;
    this.gender = gender;
    this.age = age;
  }
  //getter、和setter方法
  private String getName() {
    return name;
  }
  private void setName(String name) {
    this.name = name;
  }
  public String getGender() {
    return gender;
  }
  public void setGender(String gender) {
    this.gender = gender;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }

  public String toString(){
    return "姓名:"+name+"年龄: "+age;
  }

}

uses reflection:

package com.pb.Reflect.classinfo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import javax.swing.JOptionPane;

/*
 * 通过用户输入类的全路径,来获取该类的成员方法和属性
 * Declared获取全部不管是私有和公有
 * 1.获取访问类的Class对象
 * 2.调用Class对象的方法返回访问类的方法和属性信息
 */

  public ReflectDemo(Person p){
    Class cla=p.getClass();
    //利用Class对象的cla的自审,返回方法对象集合
    Method [] method=cla.getDeclaredMethods(); //返回所有的方法
    System.out.println("========获取方法信息============");
    for (Method meth : method) {
      //遍历method数组,并输出方法信息
      System.out.println(meth.toString());
    }
    System.out.println("========获取出方法信息结束============");
    //获取属性利用Class对象的cla的自审,返回成员属性对象集合
     Field [] field=cla.getDeclaredFields();
      System.out.println("========获取成员属性信息============");
      for (Field f : field) {
        System.out.println(f.toString());
      }
      System.out.println("========获取成员属性信息结束============");
    //获取属性利用Class对象的cla的自审,返回构造方法集合
      Constructor [] constructor=cla.getDeclaredConstructors();
      System.out.println("========获取成员构造方法信息============");
      for (Constructor constru : constructor) {
        System.out.println(constru.toString());
      }
      System.out.println("========获取成员构造方法信息结束============");
  }

}

Test Class

package com.pb.Reflect.classinfo;

public class TestReflection {

  public static void main(String[] args) {
    Person p=new Person();
    ReflectDemo rd=new ReflectDemo(p);

  }

}

========获取方法信息============
public java.lang.String com.pb.Reflect.classinfo.Person.getGender()
public void com.pb.Reflect.classinfo.Person.setGender(java.lang.String)
public int com.pb.Reflect.classinfo.Person.getAge()
public void com.pb.Reflect.classinfo.Person.setAge(int)
public java.lang.String com.pb.Reflect.classinfo.Person.toString()
private java.lang.String com.pb.Reflect.classinfo.Person.getName()
private void com.pb.Reflect.classinfo.Person.setName(java.lang.String)
========获取出方法信息结束============
========获取成员属性信息============
private java.lang.String com.pb.Reflect.classinfo.Person.name
private java.lang.String com.pb.Reflect.classinfo.Person.gender
private int com.pb.Reflect.classinfo.Person.age
========获取成员属性信息结束============
========获取成员构造方法信息============
public com.pb.Reflect.classinfo.Person()
public com.pb.Reflect.classinfo.Person(java.lang.String,java.lang.String,int)
========获取成员构造方法信息结束============

7. Chapter The .class attributes of the three method classes

Person class is the same as above

Test class:

package com.pb.Reflect.classinfo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class TestReflection {

  public static void main(String[] args) {
    /*第二种方法
    Person p=new Person();
    ReflectDemo rd=new ReflectDemo(p);
*/

    /*
     * 第三种方式.class属性
     */
    Class cla=Person.class;
    //利用Class对象的cla的自审,返回方法对象集合
        Method [] method=cla.getDeclaredMethods(); //返回所有的方法
        System.out.println("========获取方法信息============");
        for (Method meth : method) {
          //遍历method数组,并输出方法信息
          System.out.println(meth.toString());
        }
        System.out.println("========获取出方法信息结束============");
        //获取属性利用Class对象的cla的自审,返回成员属性对象集合
         Field [] field=cla.getDeclaredFields();
          System.out.println("========获取成员属性信息============");
          for (Field f : field) {
            System.out.println(f.toString());
          }
          System.out.println("========获取成员属性信息结束============");
        //获取属性利用Class对象的cla的自审,返回构造方法集合
          Constructor [] constructor=cla.getDeclaredConstructors();
          System.out.println("========获取成员构造方法信息============");
          for (Constructor constru : constructor) {
            System.out.println(constru.toString());
          }
          System.out.println("========获取成员构造方法信息结束============");
  }

}

Result:

Same as above

========获取方法信息============
public java.lang.String com.pb.Reflect.classinfo.Person.getGender()
public void com.pb.Reflect.classinfo.Person.setGender(java.lang.String)
public int com.pb.Reflect.classinfo.Person.getAge()
public void com.pb.Reflect.classinfo.Person.setAge(int)
public java.lang.String com.pb.Reflect.classinfo.Person.toString()
private java.lang.String com.pb.Reflect.classinfo.Person.getName()
private void com.pb.Reflect.classinfo.Person.setName(java.lang.String)
========获取出方法信息结束============
========获取成员属性信息============
private java.lang.String com.pb.Reflect.classinfo.Person.name
private java.lang.String com.pb.Reflect.classinfo.Person.gender
private int com.pb.Reflect.classinfo.Person.age
========获取成员属性信息结束============
========获取成员构造方法信息============
public com.pb.Reflect.classinfo.Person()
public com.pb.Reflect.classinfo.Person(java.lang.String,java.lang.String,int)
========获取成员构造方法信息结束============

The above is the detailed content of Detailed explanation of examples of reflection mechanism in Java. For more information, please follow other related articles on the PHP Chinese website!

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools