Reprint please indicate the source: blog.csdn.net/forezp/arti… This article is from Fang Zhipeng’s blog

Reflection mechanism is in the running state, for any class, can know all the attributes and methods of the class; For any object, you can call any of its methods and properties; This ability to dynamically retrieve information and invoke methods on objects is called the Reflection mechanism of the Java language. 【 translated in official document 】

This article will cover reflection from the following aspects:

  • The use of the calss
  • Reflection of method
  • Constructor reflection
  • Reflection of member variables

What is the class class

In an object-oriented world, everything is an object. Classes are objects, and classes are instance objects of the Java.lang. Class Class. In addition, class classes can only be new in Java virtual machines. 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");

// An instance object of a class can be created by its type
User user=(User)c1.newInstance();
}
Copy the code

Dynamic loading of the class

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

3. Obtain method information

The basic data types, the void keyword are instances of the Class; You can do this by getting ame(); 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());Copy the code

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());

        /** * a member method is a method object * getMethod() all public methods, including the parent class's inherited public * getDeclaredMethods() all methods of the class, including private, but not inherited methods. * /
        Method[] methods=c.getMethods();// Get method
        // Get all methods, including private, c.getdeclaredMethods ();

        for(int i=0; i<methods.length; i++){// Get the return type of the method
            Class returnType=methods[i].getReturnType();
            System.out.print(returnType.getName());
            // Get the 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(")"); }}Copy the code
public class ReflectTest {

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

Run:

The name of the class: java.lang.string

booleanequals(java.lang.Object,)

java.lang.StringtoString()

inthashCode()

Get information about member variables

You can also get information about a class’s member variables


 public static void printFiledInfo(Object o){

        Class c=o.getClass();
        /** * getFileds() public * getDeclaredFields() get all */
        Field[] fileds=c.getDeclaredFields();

        for(Field f:fileds){
            // Get the type of the member variable
            Class filedType=f.getType();
            System.out.println(filedType.getName()+""+f.getName()); }}Copy the code
 public static void main(String[] args){
                String s="ss";
                //ClassUtil.printClassInfo(s);
                ClassUtil.printFiledInfo(s);
        }
Copy the code

Run:

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

Get constructor information

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

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

            Class[] typeParas=con.getParameterTypes(a);
            for (Class class1:typeParas){
                System.out.print(class1.getName() +",");
            }
            System.out.println(")");}}Copy the code
 public static void main(String[] args){
                String s="ss";
                //ClassUtil.printClassInfo(s);
                //ClassUtil.printFiledInfo(s);
                ClassUtil.printConstructInfo(s);
        }
Copy the code

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 ,)

Six, method reflection operation

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

Method reflection operation:

method.invoke(Object, parameter list);
Copy the code

Here’s an example:

class A{

    public void add(int a,int b){
        System.out.print(a+b);
    }

    public void toUpper(String a){
        System.out.print(a.toUpperCase()); }}Copy the code
 public static void main(String[] args) { A a=new A(); Class c=a.getClass(); try { Method method=c.getMethod("add",new Class[]{int.class,int.class});
            Method Method =c.getMethod("add",int. Class,int. Class);
            // The reflection operation of the
            method.invoke(a, 10, 10);
        }catch (Exception e){ e.printStackTrace(); }
    }
Copy the code

Run:

20

This article has covered the basic use of Java reflection to determine the class of any object at run time; Construct an object of any class at runtime; Determine which member variables and methods any class has at run time. Call a method of any object at runtime; Generate dynamic proxies.

Excellent articles recommended: