Detailed introduction and summary of Java reflection mechanism

  • 2020-05-30 20:03:33
  • OfStack

This article will cover reflection from the following aspects:

The use of class Method reflection Constructor reflection Reflection of a member variable

1. What is the class class

In an object-oriented world, everything is an object. A class is an object, which is an instance object of the java.lang.Class class. In addition, class class can only be new out of java virtual machine. Any class is an instance object of the Class class. This instance object can be expressed in three ways:


public class User{
}

public class ClassTest{
User u=new User();
 // way 1:
 Class c1=User.class;
// way 2:
Class c2=u.getClass();
// way 3:
Class c3=Class.forName("com.forezp.User");

// You can create instance objects of a class by its type 
User user=(User)c1.newInstance();
}

2. Dynamic loading of class class

Class.forName(full name of class); This method not only represents the type of the class, but also dynamically loads the class. Classes loaded at compile time are statically loaded, and classes loaded at run time are dynamically loaded.

3. Obtain method information

The basic data type, void keyword, is an instance of Class class; getame(); getSimpleName() gets the name of the class.


Class c1=String.class;
Class c2=int.class;
Class c3=void.class;
System.out.println(c1.getName());
System.out.println(c2.getSimpleName());

Get all the methods of the class and print them out:


public static void printClassInfo(Object object){
    Class c=object.getClass();
    System.out.println(" Class name: "+c.getName());

    /**
     * 1 The member method is 1 a method object 
     * getMethod() All of the  public Methods, including those inherited by the parent class  public
     * getDeclaredMethods() Gets all the methods of the class, including private , But not the inherited method. 
     */
    Method[] methods=c.getMethods();// Access method 
    // Get all methods, including private ,c.getDeclaredMethods();

    for(int i=0;i<methods.length;i++){
      // Gets the return type of the method 
      Class returnType=methods[i].getReturnType();
      System.out.print(returnType.getName());
      // Get method name: 
      System.out.print(methods[i].getName()+"(");

      Class[] parameterTypes=methods[i].getParameterTypes();
      for(Class class1:parameterTypes){
        System.out.print(class1.getName()+",");
      }
      System.out.println(")");
    }
  }

Run:


 Class name: java.lang.String
booleanequals(java.lang.Object,)
java.lang.StringtoString()
inthashCode()
 ... 

4. Get information about member variables

You can also get information about the class's member variables


 public static void printFiledInfo(Object o){

    Class c=o.getClass();
    /**
     * getFileds() To obtain public
     * getDeclaredFields() Get all the 
     */
    Field[] fileds=c.getDeclaredFields();

    for(Field f:fileds){
      // Gets the type of the member variable 
      Class filedType=f.getType();
      System.out.println(filedType.getName()+" "+f.getName());
    }

  }


public static void main(String[] args){
        String s="ss";
        //ClassUtil.printClassInfo(s);
        ClassUtil.printFiledInfo(s);
    }

Run:


[C value
int hash
long serialVersionUID
[Ljava.io.ObjectStreamField; serialPersistentFields
java.util.Comparator CASE_INSENSITIVE_ORDER
int HASHING_SEED
int hash32

5. Get information about the constructor


public static void printConstructInfo(Object o){
    Class c=o.getClass();

    Constructor[] constructors=c.getDeclaredConstructors();
    for (Constructor con:constructors){
      System.out.print(con.getName()+ " ( " );

      Class[] typeParas=con.getParameterTypes();
      for (Class class1:typeParas){
        System.out.print(class1.getName()+ "  , " );
      }
      System.out.println( " ) " );
    }
  }


 public static void main(String[] args){
        String s="ss";
        //ClassUtil.printClassInfo(s);
        //ClassUtil.printFiledInfo(s);
        ClassUtil.printConstructInfo(s);
    }

Run:


java.lang.String([B ,)
java.lang.String([B ,int ,int ,)
java.lang.String([B ,java.nio.charset.Charset ,)
java.lang.String([B ,java.lang.String ,)
java.lang.String([B ,int ,int ,java.nio.charset.Charset ,)
java.lang.String(int ,int ,[C ,)
java.lang.String([C ,boolean ,)
java.lang.String(java.lang.StringBuilder ,)
java.lang.String(java.lang.StringBuffer ,)
...

6. Operation of method reflection

Get 1 method: you need to get the name of the method and the parameters of the method to determine a method.

Method reflection operation:


Class c1=String.class;
Class c2=int.class;
Class c3=void.class;
System.out.println(c1.getName());
System.out.println(c2.getSimpleName());
0

Here's an example:


Class c1=String.class;
Class c2=int.class;
Class c3=void.class;
System.out.println(c1.getName());
System.out.println(c2.getSimpleName());
1

Class c1=String.class;
Class c2=int.class;
Class c3=void.class;
System.out.println(c1.getName());
System.out.println(c2.getSimpleName());
2

Run:


20

This article has explained the basic use of java reflection to determine at runtime which class any object belongs to; Construct the object of any one class at runtime. Determine the member variables and methods of any one class at runtime. Call methods on any one object at run time; Generate a dynamic proxy.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: