Dark Horse Programmer "reflection mechanism in Java"

Source: Internet
Author: User

The reflection mechanism in Java

-------Android Training, Java training, look forward to communicating with you! ----------

The reflection mechanism of Java is one of the characteristics of Java, the reflection mechanism is the foundation of the framework technology, using reflection can make the program more flexible, avoid writing the program to die in the code. For many beginners who have only touched the basics of Java, reflection is a very obscure concept, let's say some of the applications of reflection.

The Java reflection mechanism refers to the function of dynamically acquiring information and dynamically invoking object methods in the running state. Java reflection has 3 dynamic properties: 1. The runtime generates an object instance, 2. Call release during run, 3. Change properties at run time.

So what is the principle of reflection? Then we need to take a look at the Java program execution process, want Java program to run, Java class must be loaded by the Java virtual machine. The run program is loaded with the required classes at compile time. I have to mention here, I believe that many people for what is compiled, what is the runtime does not have a clear concept, compile time is the compiler to help you translate the code into the device can recognize the code, that is, the compiler will do some simple work at compile time, such as check your grammar there is no error, The keyword or name is written with or without errors, loading the class, which is what to do when compiling, what does the runtime do? The runtime is when your program starts, the code is loaded into memory, and the run-time check is the operation and judgment in your memory, let's take a small example:

   int New int [3];        nums[4] = 12;

Obviously, the above code will appear in the array subscript error, but the program at compile time without error, but at run time will not report a arrayindexoutofboundsexception error, which is the difference between compile time and run time.

While the Java reflection mechanism is not sure which class is loaded at compile time, it is loaded and used when the program is running, and we use a simple diagram to see the execution of the reflection:

The Java reflection mechanism is able to know the basic structure of a class, and this ability to explore Java class structures becomes "self-censoring", as is the principle of Java reflection when we use an eclipse-like software to write code with automatic hints. So what can we do with the reflection of Java? 1. At run time, judge any object belongs to class, 2. Constructs an object of any class at run time, 3. At run time, determine the properties and methods that any class has, 4. A method that invokes any object at run time. Java reflection commonly used classes have class: Reflection of the core class, through the class class can get the properties, methods and other content. Filed class: Represents a property of a class that can get and set the value of a property in a class. Method class: A way of representing a class that can be used to obtain information about a method in a class, or to execute a method. Constructor class: Represents the construction method of a class.

Well, we've got some basic information about Java reflection, so let's implement each of the functions of reflection in a code-based way:

The first, but also the simplest, first to use, class classes must first instantiate him, but class does not have a method of construction, then we have to instantiate it, there are three ways to create class classes:

 Public Static voidMain (string[] args) {//the first method, through the object. GetClass () methodUser User =NewUser (); Class<?extendsUser> cs =User.getclass ();                SYSTEM.OUT.PRINTLN (CS); //the second method, through the class name. classclass<user> CS1 = User.class;                System.out.println (CS1); //The third method, through the forname () method of the class itself, notes that the forname () method throws the same, and that the parameters inside require a complete package name and class nameClass<?>CS2 = null; Try{CS2= Class.forName ("Cn.fanfu.demo.User"); } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace ();    } System.out.println (CS2); }

The third type of forname () method can be more flexible by instantiating class in the case of uncertain classes.

The second is to create a new instance of the class object by using the class's argument structure:

     Public Static voidMain (string[] args)throwsclassnotfoundexception, SecurityException, Nosuchmethodexception, IllegalArgumentException, Instantiationexception, Illegalaccessexception, invocationtargetexception {//for a more intuitive display, use the String class directly hereClass<?> CS =class.forname ("java.lang.String"); Char[] ch = {' big ', ' home ', ' good ', '! ‘,‘! ‘}; //call the class's parameter constructor, and the value in the function is classes. classconstructor<?> CST = Cs.getconstructor (Char[].class); String name=(String) cst.newinstance (CH);       SYSTEM.OUT.PRINTLN (name); //because the exception here makes the code not visually visible, I throw it directly to the virtual machine}

The third is the acquisition of a class of constructs, interfaces, methods, properties, and a series of elements:

 Public Static voidMain (string[] args)throwsclassnotfoundexception, SecurityException, Nosuchmethodexception, IllegalArgumentException, Ins Tantiationexception, Illegalaccessexception, invocationtargetexception {//create two objects first.Class<?> cs = class.forname ("Cn.fanfu.demo.User"); Constructor<?>[] con =NULL; //a constructor[] array is returned through the GetConstructors () method, which stores the various constructs of the classCon =cs.getconstructors ();  for(constructor<?>Item:con)        {System.out.println (item); }        //returns a class<?>[] array through the Getinterfaces () method, which stores the various interfaces of the classClass<?>[] Inter =cs.getinterfaces ();  for(class<?>item:inter)        {System.out.println (item); }        //returns a class<?> by using the Getsuperclass () methodclass<?> parent =Cs.getsuperclass (); //Only single inheritance is supported in Java, so there is only one parent classSystem.out.println (parent); //returns a method[] array through the GetMethods () method, in which the various methods of the class are stored in the array.Method[] Method =Cs.getmethods ();  for(Method item:method) {System.out.println (item); }        //returns a field[] array with the Getdeclaredfields () method, which stores the various properties of the classfield[] Fiel =Cs.getdeclaredfields ();  for(Field Item:fiel) {System.out.println (item); }        //the Getdeclaredfields () method can get all the properties, and the GetFields () method can only get to the public propertyfield[] Fiel1 =Cs.getfields ();  for(Field item:fiel1) {System.out.println (item); }    }

The fourth is to get or modify the value of a class's properties:

 Public Static voidMain (string[] args)throwsclassnotfoundexception, SecurityException, Nosuchmethodexception, IllegalArgumentException, Ins Tantiationexception, Illegalaccessexception, InvocationTargetException, nosuchfieldexception {//creating a User ObjectUser US =NewUser (); Us.setage (12); Us.setname ("Zhang San"); Class<?> cs =Us.getclass (); //gets the value of the private propertyField fl = Cs.getdeclaredfield ("name"); //to set the Allow access firstFl.setaccessible (true); //To specify an object get value by a Get methodString name =(String) fl.get (US);        SYSTEM.OUT.PRINTLN (name); //specifying objects and modifying values through the Set methodFl.set (US, "John Doe"); String name2=(String) fl.get (US);            System.out.println (name2); }

The fifth one is to invoke the method by reflection:

 Public Static voidMain (string[] args)throwsclassnotfoundexception, SecurityException, Nosuchmethodexception, IllegalArgumentException, Ins Tantiationexception, Illegalaccessexception, InvocationTargetException, nosuchfieldexception {//creating a User ObjectUser US =NewUser (); Us.setage (12); Us.setname ("Zhang San"); Class<?> cs =Us.getclass (); //gets the method in the class by the GetMethod () method, which has two parameters, a specified method name, and a type of the parameter in the specified methodMethod mm = Cs.getmethod ("Say"); //The method is called by the Invoke () method, which has two parameters, one for the specified object, and another for the pass parameterMm.invoke (US); }

Well, the introduction of reflection on the first so much, and some other columns such as the array of operations, are some of the workarounds, do not introduce more.

Dark Horse Programmer "reflection mechanism in Java"

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.