English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Introduction and summary of reflection mechanism usage in Java programming

This article describes the usage of Java reflection mechanism. Shared for everyone's reference, as follows:

Introduction:Reflection: Dynamically obtain a class (byte code file such as Person.class in this article) and execute its members. Reflection may be slightly less common in the development of Android application layers, but it is essential for those who want to delve into the lower layers.

Entity class

Person.java

package com.sunwenou.reflect;// Package name
public class Person {
  private String name;
  private int age;
  public Person() {// No parameters
  }
  public Person(String name, int age) {// Parameterized
    super();
    this.name = name;
    this.age = age;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  @Override
  public String toString() {
    return name+","+age;
  }
  public void show() { // No parameters
    System.out.println("show");
  }
  public void fun(String ss) { // Parameterized
    System.out.println(ss);
  }
  public static void function() { // Static
    System.out.println("static");
  }
}

Dynamically obtain the bytecode file method

In this article, for the sake of brevity, exceptions are thrown all over and imports are omitted as usual.

package com.sunwenou.reflect;
public class Demo1 {
  /**
   * Dynamically obtain the bytecode file method
   * 1: Use the Class getClass() method provided by Object class
   *  : This method requires an object
   * 2: Each data type has a static class attribute, which returns the bytecode file object of this data type
   *  int.class  Person.class
   * 3: use the forName() method provided by Class
   *  You only need to provide a string, which consists of the package name+Class name composition
   */
  public static void main(String[] args) throws Exception {
    //getClaz();
    //getCalz2();
    getClaz3();
  }
  //Use the forName() method provided by Class
  public static void getClaz3() throws Exception {
    Class<?> claz = Class.forName("com.sunwenou.reflect.Person");
    Class<?> claz2 = Class.forName("com.sunwenou.reflect.Person");
    System.out.println(claz==claz2);
  }
  //Each data type has a static class attribute
  public static void getCalz2() {
    Class<Person> p1 = Person.class;
    Class<Person> p2 = Person.class;
    System.out.println(p1==p2);
  }
  //Use the Class getClass() method provided by the Object class
  public static void getClaz() {
    Person person1 = new Person();
    Class<? extends Person> claz = person1.getClass();//Person.class
    Person person2 = new Person();
    Class<? extends Person> claz2 = person2.getClass();//Person.class
    System.out.println(claz==claz2);
  }
}

Dynamically obtain the class and create an object

package com.sunwenou.reflect;
public class Demo2 {
  public static void main(String[] args) throws Exception {
    //createObj();
    createObj2();
  }
  public static void createObj2() throws Exception {
    //Person person = new Person("lisi",23);
    //Get the bytecode file object
    Class<?> claz = Class.forName("com.sunwenou.reflect.Person");//Person.class
    //Get the Constructor type object belonging to the method with parameters
    Constructor constructor = claz.getConstructor(String.class,int.class);
    //Create an object using the method provided by the Constructor class
    Person person = (Person)constructor.newInstance("lisi",23);
    System.out.println(person);
  }
  public static void createObj() throws Exception {
    //Person person = new Person();
    //Get the bytecode file object
    Class<?> claz = Class.forName("com.sunwenou.reflect.Person");
    Object obj = claz.newInstance();//The default constructor with no parameters is used to create an object
    System.out.println(obj);
  }
}

Dynamically obtain the class and assign values to member variables

package com.sunwenou.reflect;
public class Demo3 {
  public static void main(String[] args) throws Exception {
    //Person p = new Person();
    //p.name = "lisi";
    //Get the bytecode file object
    Class<?> claz = Class.forName("com.sunwenou.reflect.Person");
    //Get the Constructor type object belonging to the method with parameters
    //Field field = claz.getField("name");//Get the member variable belonging to the Field type object
    Field field = claz.getDeclaredField("name");//Get all declared fields
    System.out.println(field);
    //Non-static member variables are dependent on objects
    Object obj = claz.newInstance();
    field.setAccessible(true);//Brute force, set as accessible
    field.set(obj, "张三");
    System.out.println(obj);
  }
}

Dynamically obtain the class and execute the method

package com.sunwenou.reflect;
public class Demo4 {
  public static void main(String[] args) throws Exception {
    //method1();
    method2();
    method3();
  }
  public static void method3() throws Exception {
    //Get the bytecode file object
    Class<?> claz = Class.forName("com.sunwenou.reflect.Person");
    Method m = claz.getMethod("function", null);
    m.invoke(null, null);
  }
  ////Execute a method with parameters
  public static void method2() throws Exception {
    //Get the bytecode file object
    Class<?> claz = Class.forName("com.sunwenou.reflect.Person");
    Method m = claz.getMethod("fun", String.class);
    Object obj = claz.newInstance();
    m.invoke(obj, "hello");
  }
  //Execute parameterless method
  public static void method1() throws Exception {
    //Person person = new Person(); person.show();
    //Get the bytecode file object
    Class<?> claz = Class.forName("com.sunwenou.reflect.Person");
    //Get the bytecode file object of the method to be executed
    Method m = claz.getMethod("show", null);
    //Non-static methods depend on objects
    Object obj = claz.newInstance();
    //Execute method
    m.invoke(obj, null);
  }
}

This is the basic usage of reflection. We can create objects through the bytecode file of the object when we cannot create objects normally, and execute the methods in it. Did you learn it??

Readers who are interested in more Java-related content can check the special topics on this site: 'Java Object-Oriented Programming入门与进阶教程', 'Java Data Structures and Algorithms Tutorial', 'Summary of Java DOM Node Operation Skills', 'Summary of Java File and Directory Operation Skills', and 'Summary of Java Caching Operation Skills'.

I hope the description in this article is helpful to everyone's Java program design.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously, and this website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You may also like