Home  >  Article  >  Java  >  Detailed introduction to Java reflection mechanism knowledge summary

Detailed introduction to Java reflection mechanism knowledge summary

黄舟
黄舟Original
2017-03-18 11:23:021283browse

The reflection mechanism is that in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties; this dynamic acquisition The information and the function of dynamically calling the object's methods are called the reflection mechanism of the Java language. [Translated from official documents]

This article will introduce the knowledge of reflection from the following aspects:

1. What is a class class

In the object-oriented world, everything is an object. Classes are objects, and classes are instance objects of the java.lang.Class class. In addition, the class class can only be new by the Java virtual machine. Any class is an instance object of the Class class. This instance object has three expressions:

public class User{
}

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

//可以通过类的类型创建该类的实例对象
User user=(User)c1.newInstance();
}

2. Dynamic loading of class class

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

3. Obtaining method information

Basic data types, void keywords are instances of the Class class; the name of the class can be obtained through getame();getSimpleName() .

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("类的名称:"+c.getName());

        /**
         * 一个成员方法就是一个method对象
         * getMethod()所有的 public方法,包括父类继承的 public
         * getDeclaredMethods()获取该类所有的方法,包括private ,但不包括继承的方法。
         */
        Method[] methods=c.getMethods();//获取方法
        //获取所以的方法,包括private ,c.getDeclaredMethods();

        for(int i=0;i
public class ReflectTest {

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

Run:

类的名称:java.lang.String
booleanequals(java.lang.Object,)
java.lang.StringtoString()
inthashCode()
…

4. Get the information of member variables

You can also get the member variable information of the class

 public static void printFiledInfo(Object o){

        Class c=o.getClass();
        /**
         * getFileds()获取public
         * getDeclaredFields()获取所有
         */
        Field[] fileds=c.getDeclaredFields();

        for(Field f:fileds){
            //获取成员变量的类型
            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 the constructor information

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.char
set
.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 a method: You need to get the name of the method and the parameters of the method to determine a method.

Reflection operation of method:

method.invoke(对象,参数列表);

For 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());
    }
}
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);
            //方法的反射操作
            method.invoke(a,10,10);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

Run:

20

The above is the detailed content of Detailed introduction to Java reflection mechanism knowledge summary. 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