java reflection mechanism and application

A, Java reflection mechanism

  1. Definition:
    reflection: Functional analysis program capable of.
    . Reflection: a in the operating state, for any class, are made known to all properties and methods of this class; b. For any object, are able to call any of its methods and properties;.
            Information acquired this dynamic and reflection dynamic invocation object's function method is called the java language.

  2. Mechanism of action of reflection:
    A function runtime class analysis.
    B view object runs.
    C. to achieve a common operation target array.
    D. using Method object.

  3. Principle
    runtime system for all Java objects always maintain type identifier is known as a run-time.
    This information is tracked for each object belongs to a class. Virtual machine type information to select the appropriate method for runtime execution.
    Access this information through special Java classes. Save the information class is called Class, the name is confusing. GetClass Object class () method will return an instance of Class type.

Second, the use of Java reflection mechanism

  1. GetClass Object class () method will return an instance of Class type.
    . A loaded object classes, Class Object
            Class cl = Class.getClass ();
    for example:
    creating classes User.java entity classes.
User user = new User();
//返回类对象
Class cl = user.getclass();    
//返回类的名称
String name = cl.getName();

        . b forName static method to obtain the object class name corresponding to Class
        Class cl = Class.forName ( "class packet class name.");

String dassName = "java.util .Random";
Class cl = Cl ass.forName(dassName);
  1. newInstances (): dynamically create an instance of a class
    , for example:
//默认使用类的无参构造方法
User user;
user.getClass().newlnstance();

Supplementary:
         c obtain a class field.

Class cl;
Field f  = cl.getField(String name);  //指定的字段
Field f  = cl.getDeclaredField(String name); //指定的字段,需要在修改字段值时必定设置可访问性
f.setAccessible(true);	//设置可访问性

         d. obtaining class methods

Class cl;
Method m = cl.getMethod(方法名);
Method m = cl.getDeclaredMethod(方法名,Class... pType);
		
//访问方法之前,设置可访问性
m..setAccessible(true);
		
//执行方法
Object obj = m.invoke(实例的对象,Class... agrValue)

Reference: "Java core technology"

Published 16 original articles · won praise 3 · Views 539

Guess you like

Origin blog.csdn.net/outdata/article/details/99747474