Dark Horse Programmer-java Basics-Reflection Basics

Source: Internet
Author: User

-------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[] Nums = 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 void Main (string[] args) {        //first method, through object. GetClass () method        User user = new user ();        class<? Extends user> cs = User.getclass ();        SYSTEM.OUT.PRINTLN (CS);                The second method, through the class name. class        class<user> cs1 = user.class;        System.out.println (CS1);                The third method, through the forname () method of the Class itself, notices that the forname () method throws the same, and that the parameters inside require the full package name and class name        class<?> CS2 = null;        try {            CS2 = Class.forName ("Cn.fanfu.demo.User");        } catch (ClassNotFoundException e) {            //TODO Auto-generated Catch block            e.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 void Main (string[] args) throws ClassNotFoundException, SecurityException, Nosuchmethodexception, IllegalArgumentException, Instantiationexception, Illegalaccessexception, invocationtargetexception {      // Here for more intuitive display, direct use of the String class       class<?> 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. class       constructor<?> 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, so 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 void Main (string[] args) throws ClassNotFoundException, SecurityException, Nosuchmethodexception,  IllegalArgumentException, Instantiationexception, Illegalaccessexception, invocationtargetexception        {//Create two objects first class<?> cs = class.forname ("Cn.fanfu.demo.User");        Constructor<?>[] con = null;        Returns a constructor[] array through the GetConstructors () method, which stores the various constructs of the class con = Cs.getconstructors ();        for (constructor<?> Item:con) {System.out.println (item);        }//The Getinterfaces () method returns a class<?>[] array in which the various interfaces of the class are stored class<?>[] inter = cs.getinterfaces ();        for (class<?> item:inter) {System.out.println (item);        }//Returns a class<?> class<?> parent = Cs.getsuperclass () through the Getsuperclass () method;        Only single inheritance is supported in Java, so there is only one parent class System.out.println (parent); The GetMethods () method returns a method[] array in which the various methods of the class are stored 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 class field[] 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 property field[] 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 void Main (string[] args) throws ClassNotFoundException,            SecurityException, Nosuchmethodexception, IllegalArgumentException,            instantiationexception, Illegalaccessexception,            invocationtargetexception, nosuchfieldexception {        //Create user Object        User US = new user ();        Us.setage (n);        Us.setname ("Zhang San");        Class<?> cs = Us.getclass ();        Gets the value of the private property        Field fl = Cs.getdeclaredfield ("name");        To set the Allow access to        fl.setaccessible first (true);        Gets the value by specifying the object by the Get method        String name = (string) fl.get (US);        SYSTEM.OUT.PRINTLN (name);        Specify the object by the Set method and modify        the value Fl.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 void Main (string[] args) throws ClassNotFoundException,            SecurityException, Nosuchmethodexception, IllegalArgumentException,            instantiationexception, Illegalaccessexception,            invocationtargetexception, nosuchfieldexception {        //Create user Object        User US = new user ();        Us.setage (n);        Us.setname ("Zhang San");        Class<?> cs = Us.getclass ();        The method in the class is obtained by the GetMethod () method, which has two parameters, a specified method name, and a type of the parameter in the specified method        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 parameter        mm.invoke (US);    

Dark Horse Programmer-java Basics-Reflection Basics

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.