Java had a basis (a) reflection

A, reflection is Gesha

  Is defined : in the operating state dynamically acquiring the class information and dynamic invocation object method , this function is called reflection java language.

  • For any class, we are able to know all the properties and methods of this class.
  • For any object, you can call any of its methods and properties.

Two, Class Objects

  Definitions  : Every class in our development process, but also to create an object that is an instance of an object class itself java.lang.Class class, we call this instance of the object is a class object, which is the Class object.

  Before learning reflection we should first understand what a class object:

  • Instance of an object class Class represent classes and interfaces Java applications running in.
  • Jvm There are a lot of instances, each class has a unique Class object. Class no public class constructor.
  • Class objects are constructed automatically when the class is loaded by the Java virtual machine. That we do not need to create, JVM has helped us create.
  • Class object type for providing information itself, such methods have several configurations, number of properties, which have an ordinary method.

  There are several ways to obtain the Class object:

  • Class.forName () (common)
  • Test.class
  • new Test().getClass()
/ ** 
 * reflection Demo 
 * / 
public  class the Test {
     public  static  void main (String args []) throws Exception {
         / * three methods of obtaining a class object * / 
        // . 1, the Class.forName () (common) 
        Class = Class1 the Class.forName ( "zhbf.web.Test" );
         // 2, Test.class 
        class Class2 = the Test. class ;
         // . 3, the Test new new () getClass (). 
        class = Class3 new new the Test (). getClass (); 

        / * class object created three ways to invoke a method in which the * /
        Method method1 = class1.getMethod("printSome",String.class);
        method1.invoke(class1, "class1");
        Method method2 = class2.getMethod("printSome",String.class);
        method2.invoke(class2, "class2");
        Method method3 = class3.getMethod("printSome",String.class);
        method3.invoke(class3, "class3");
    }

    public static void printSome(String className) {
        System.out.println(className + "通过反射机制获取方法并调用~");
    }
}

Run the main method:

Third, create objects using the reflection mechanism

step:

/ * Create object process * / 
// 1. Get the object class 
Class ClassTest the Class.forName = ( "zhbf.web.Test" );
 // 2. Get the object constructor (the constructor parameter of the parameter type of method selected ) 
the Constructor CON = ClassTest. getConstructor ();
 // . 3 acquires the object 
the Test Test = (the Test) CON. the newInstance ();
  • getConstructors ()  : all "public domain" construction method
  • getDeclaredConstructors ()  : Gets all the constructors (including private, protected, default, public) 
  • getConstructor (parameter type constructor)  : Get a single "communal" constructor
  • getDeclaredConstructor (parameter type constructor)  : acquiring "a construction method" can be private, or protected, default, public;
  • newInstance () : Gets the object

Fourth, acquire and use the member variables

Common methods:

  • getField (property name)  : You can get the public, including inherited from the parent class of the field .
  • getDeclaredField (property name)  : Get This class field including public, private and proteced, but can not get inherited fields .
  • getDeclaredFields () : get all the fields declared in a class, which includes public, private and proteced, but does not include the stated fields of the parent class .
  • setAccessible (Boolean value) : Set the variable is accessible
/ * Obtain and modify the attributes * / 
ZhbfwebApplicationTests testClass = new new ZhbfwebApplicationTests ();
 // get ZhbfwebApplicationTests access to private class variable name 
Field, Field, = Class.forName ( "zhbf.web.ZhbfwebApplicationTests"). GetDeclaredField ( "name" );
 // set variables can be accessed (ture) 
Field,. setAccessible ( to true );
 // after setting step on, can be re-assigned to the private variable 
field.set (testClass, "WLx" );
 // print objects from testClass name of variable to obtain 
System.out.println (field.get (testClass));

Fifth, the acquisition and use member method

Common methods:

  • getMethod (method name, the argument types)   : Get "public methods"; (parent class contains the method also comprises the Object class)
  • getDeclaredMethods (method name, the argument types)   : Get member methods, including private (not including inherited)
  • invoke (Object, parameters) : call the method
// call the method and pass parameters 
Class class1 = the Test. Class ; 
Method, Method, . = Class1 getMethod ( "printSome", String. Class ); 
Method,. The Invoke (class1, "class1");

Sixth, the reflection of common applications

  Reflected common scenarios are as follows:

Spring Framework configuration file design

  Spring Framework configuration file is usually named application.properties , common configuration is generally written in here, why should the public in this way to write the message?

  Scene For example : For example, we need to configure the database connection information:

  • Written in the code , modify the database connection address will need to be recompiled, rather cumbersome .
  • Written in a configuration file, use reflection to read , without recompilation, only you need to modify a single configuration file contents like.

Code:

/ ** 
 * reflection read file 
 * / 
public  class the Test { 

    public  static  void main (String args []) throws Exception {
         // get the class name and method name from the application.properties 
        File springConfigFile = new new File ( "E: MyOwnGit \\ \\ ZHBF ZHBF \\ the WEB-main \\ src \\ \\ \\ application.properties Resources " );
         // the Properties is a Java language configuration file used by classes, Xxx.properties common language for the Java profile 
        the Properties springConfig = new new the Properties ();
         // file to read the file input stream content 
        springConfig.load ( new new the FileInputStream (springConfigFile)); 
        String driverClass= (String) springConfig.get("spring.datasource.driver-class-name");
        String url = (String) springConfig.get("spring.datasource.url");
        String username = (String) springConfig.get("spring.datasource.username");
        String password = (String) springConfig.get("spring.datasource.password");
        System.out.println("=====输出数据库配置=====");
        System.out.printf("驱动类:%s url:%s 用户名:%s 密码:%s", driverClass, url, username, password);
    }

}

Output:

After modifying the configuration file output:

Guess you like

Origin www.cnblogs.com/riches/p/12069323.html