A detailed example of Java reflection mechanism

  • 2020-10-31 21:46:42
  • OfStack

A detailed example of Java reflection mechanism

Is JAVA a dynamic language?

Generally speaking, when speaking of dynamic language, it is allowed to change the program structure or variable type while the program is running. From this point of view, Java and C++1 are not dynamic languages.

JAVA, however, has a very prominent dynamic correlation mechanism: reflection. With reflection, Java can load, probe, and use classes that are fully summed at compile time, generate their object entities, call their methods, or set values on properties at run time. So Java is a semi-dynamic language.

The concept of reflection:

In Java, the reflection mechanism means that all properties and methods of any class can be known in the running state.

For any one object, you can call any one of its methods;

This ability to get information on the go and call object methods on the go is called the Java language's reflection mechanism

2. Dynamic nature

2.1 Dynamic properties

Runtime generation of object instances;
Call a method during run time;
Change properties at runtime

2.2 Functions of Java reflection mechanism

Determines the class to which any 1 object belongs at runtime
Construct an object of any 1 class at run time
At run time, determine the methods and properties of any class
A method that invokes any 1 object at run time
Generate dynamic proxy

2.3 Java Reflection applications

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

The type at compile time is determined by the type used when the object is declared, and the type at run time is determined by the type actually assigned to the object

Such as:


Person p =new Student();

The type is Person at compile time and Student at run time

In addition, the program may receive an object at run time that is of compile time type Object, but the program needs to call a method of that object's runtime type. For these problems, the program needs to discover real information about objects and classes at run time. However, if compilation cannot predict which classes the object and class might belong to at all, and the program relies only on runtime information to discover the true information about the object and class, then reflection must be used

Java Reflection API

Reflect the information that API USES to generate classes, interfaces, or objects in the current JAVA virtual machine.

Class class: the core class of reflection, which can obtain the properties, methods and other content information of the class.
Field class: Java. lang. reflect. Represents the property of the class, and you can get and set the value of the middle property of the class.
Method classes: Java. lang. reflect. A method representing a class that can be used to obtain information about a method in a class or to execute a method
Construcor classes: Java. lang. reflect. Represents the constructor of a 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 , and setter methods 
  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: "+name+" age : "+age;
  }

}

Using 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;

/*
 *  The member methods and properties of a class are obtained by entering the full path of the class from the user 
 * Declared Get everything both private and public 
 * 1. Gets access to the class Class object 
 * 2. call Class Object returns method and property information for accessing the class 
 */
public class ReflectDemo {

  /*
   *  A constructor 
   */
  public ReflectDemo(){
    // The full path of the user input class 
    // use String component 
    String classpsth=JOptionPane.showInputDialog(null," The full path of the input class ");
    // use Class.forName Method based on the full path of the input class   Return the Class object 
    try {
      Class cla = Class.forName(classpsth);
      // using Class The object's cla The self-examination , Returns a collection of method objects 
      Method [] method=cla.getDeclaredMethods(); // Returns all methods 
      System.out.println("======== Get method information ============");
      for (Method meth : method) {
        // traverse method Array, and output method information 
        System.out.println(meth.toString());
      }
      System.out.println("======== The end of getting the method information ============");
      // Get attribute utilization Class The object's cla The self-examination , Returns a collection of member property objects 
       Field [] field=cla.getDeclaredFields();
        System.out.println("======== Gets member property information ============");
        for (Field f : field) {
          System.out.println(f.toString());
        }
        System.out.println("======== End of getting member property information ============");
      // Get attribute utilization Class The object's cla The self-examination , Returns a collection of constructor methods 
        Constructor [] constructor=cla.getDeclaredConstructors();
        System.out.println("======== Gets member constructor information ============");
        for (Constructor constru : constructor) {
          System.out.println(constru.toString());
        }
        System.out.println("======== End of getting member constructor information ============");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
      System.out.println(" Path input error! ");
    }
  }

}


package com.pb.Reflect.classinfo;

public class TestReflection {

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

  }

}

Input com. pb. Reflect. classinfo. Person

Results:


======== Get method information ============
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)
======== The end of getting the method information ============
======== Gets member property information ============
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
======== End of getting member property information ============
======== Gets constructor information ============
private com.pb.Reflect.classinfo.Person()
public com.pb.Reflect.classinfo.Person(java.lang.String,java.lang.String,int)
======== End of getting constructor information ============

Step 5 Use reflection

5.1, steps,

Java.lang.reflect

Gets the ES117en. lang. Class object for the class you want to manipulate
Call the Class method
Use reflection API to manipulate this information

5.2. Get Class object method

Call the getClass() method of an object


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

Call the class attribute of a class to get the corresponding Class object of that class


Class cls=Person.class;

Use the forName() static method of the Class class


Class cla=Class.forName( "Full Path to class" );

6. getClass() method of the second method object

The Person class will construct the method public because you want to declare an object


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 , and setter methods 
  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: "+name+" age : "+age;
  }

}

Using 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;

/*
 *  The member methods and properties of a class are obtained by entering the full path of the class from the user 
 * Declared Get everything both private and public 
 * 1. Gets access to the class Class object 
 * 2. call Class Object returns method and property information for accessing the class 
 */

  public ReflectDemo(Person p){
    Class cla=p.getClass();
    // using Class The object's cla The self-examination , Returns a collection of method objects 
    Method [] method=cla.getDeclaredMethods(); // Returns all methods 
    System.out.println("======== Get method information ============");
    for (Method meth : method) {
      // traverse method Array, and output method information 
      System.out.println(meth.toString());
    }
    System.out.println("======== The end of getting the method information ============");
    // Get attribute utilization Class The object's cla The self-examination , Returns a collection of member property objects 
     Field [] field=cla.getDeclaredFields();
      System.out.println("======== Gets member property information ============");
      for (Field f : field) {
        System.out.println(f.toString());
      }
      System.out.println("======== End of getting member property information ============");
    // Get attribute utilization Class The object's cla The self-examination , Returns a collection of constructor methods 
      Constructor [] constructor=cla.getDeclaredConstructors();
      System.out.println("======== Gets member constructor information ============");
      for (Constructor constru : constructor) {
        System.out.println(constru.toString());
      }
      System.out.println("======== End of getting member constructor information ============");
  }

}

The test 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 , and setter methods 
  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: "+name+" age : "+age;
  }

}

0

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 , and setter methods 
  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: "+name+" age : "+age;
  }

}

1

7. class attribute of the third method class

Person similar on

The test 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 , and setter methods 
  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: "+name+" age : "+age;
  }

}

2

Results:

Same as above


======== Get method information ============
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)
======== The end of getting the method information ============
======== Gets member property information ============
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
======== End of getting member property information ============
======== Gets member constructor information ============
public com.pb.Reflect.classinfo.Person()
public com.pb.Reflect.classinfo.Person(java.lang.String,java.lang.String,int)
======== End of getting member constructor information ============

If you have any questions, please leave a message or go to this site community exchange discussion, thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: