The Java reflection of the thick product Thin hair series

Source: Internet
Author: User

Niche, in the case of Java reflection just stay on the basis of simple and practical, let's combine the simple case to understand the Java reflection

1. Prepare the test prepare two classes and a test class with the Main method

  • Test1 class
     package   reflection;  public  class   Test1 { public  void   Test () {System.out.println (" Test1 method "); }}  

     

  • Test2 class
     package   reflection;  public  class   Test2 { public  void   Test () {System.out.println (" Test2 method "); }}  

     

  • Test class with the Main method
     Package reflection;  Public class Main {    publicstaticvoid  main (string[] args) {        new  Test1 (). Test ();}    }

2. Requirements are now running in the main method is the test () method that runs the Test1 testing class if we have a need to replace the test () method in the Test2 class we have two methods

  • Traditional methodsModify Codere-compilingCan
    1  Packagereflection;2 3  Public classMain {4 5      Public Static voidMain (string[] args) {6         //new Test1 (). Test ();7         NewTest2 (). Test ();8 9     }Ten  One}

  • The method of using reflection Pros : No code changesNo recompilation
    • Provides a configuration file such as Spring.txt used to store the fully qualified name of two classes
      Class=reflection. Test2

    • Rewrite the Main method
      Package Reflection;import Java.io.file;import Java.io.fileinputstream;import java.io.filenotfoundexception;import Java.io.ioexception;import Java.lang.reflect.constructor;import Java.lang.reflect.method;import Java.util.properties;public class Main {public static void main (string[] args) throws Exception, IOException {///Traditional Change Code Party Method//New Test1 (). Test ();//New Test2 (). Test ();//rewrite to load a class using reflection dynamics//1 load Spring.txt configuration file read the class you configured to use The next time you change the class directly, you can change the file File = new file ("J:\\ecplisework\\testother\\src\\spring.txt") in the profile. Create an object that reads the configuration file propertiesproperties springtxt = new Properties ();//causes the profile object to read the contents of the Spring.txt springtxt.load (new FileInputStream (file));//Gets the class's fully qualified name string className = Springtxt.getproperty ("class") by getting the value of class in Spring.txt;// Creates a class object based on the fully qualified name class class<?> Clazz = Class.forName (className);//Gets the method object, M = Clazz.getmethod ("test");// Gets the constructor constructor<?> C = Clazz.getconstructor ();//An object based on the constructor instance objects object = C.newinstance ();// Invokes the specified method of the specified instance M.invoke (object);}}

    • Summary: Using the Reflection method does not have to change the Java code and does not have to recompile the class file can be dynamically reflected from the configuration file load a class and run its methods, only need to change the configuration file

3. Why use reflection & reflection in those scenarios

    • The normal process of creating a class new Object (): When the JVM starts, all the written classes are compiled into a. class file, which is then loaded into the JVM's memory by the ClassLoader, and when an instance of a class needs to be created, the JVM checks to see if the class is loaded. After loading, look for the corresponding. Class object and allocate memory for the instance;
    • Suddenly-------we suddenly want to run a class that doesn't load into the JVM's memory?????  There is no such object in the JVM. How to do wood????? Then reflection can help us
    • Common scenarios such as when loading data drivers, you can choose to use a MySQL database or an Oracle database through a configuration file

4. How to better use reflection?

  • role: in the Java Runtime environment, for any class, you can know what properties and methods the class has. For any one object, you can call any of its methods. This dynamic acquisition of information for classes and the ability to dynamically invoke objects is derived from the Java language's reflection (Reflection) mechanism.
  • The reflection mechanism of Java mainly provides the function key sub: at run time
      • Determine the class to which an arbitrary object belongs at run time
      • Constructs an object of any class at run time
      • Determine the member variables and methods that any class has at run time
      • Methods that invoke arbitrary objects at run time
  • Common methods
    • Get Object Type
      Class<?> clazz = class.forname ("Permission naming of the class");
      class<? Extends test2> class1 = This.getclass ();

      CLASSC2 =test1.  class;

    • Get constructor
      Constructor<?>[] Constructors = clazz.getconstructors (); Get all public constructors for a class

        

    • How to get field information
       1  String name = clazz.ge Tfield ("password"). GetName (); //  2  field[] fields = Clazz.getfields (); //  get all public fields  3  Field Declaredfield = Clazz.getdeclaredfield ("username"); //  Gets the named field of the class declaration  4  field[] declaredfields = Clazz.getdeclaredfields (); //  Gets the field of all class declarations  

       

    • Get method information
      1         //  2         //3         //4         //  Get all methods of class declaration

The Java reflection of the thick product Thin hair series

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.