Java Reflection mechanism

Source: Internet
Author: User
Tags object object print object

Recently learning to meet the reflection mechanism, but the teacher is just an understatement to explain a pass, or self-check information to add a bit.

The Java reflection mechanism is in the running state, for any class, can know all the properties and methods of this class, for any one object, can call any of its methods and properties; This dynamically acquired information and the ability to dynamically invoke the object's methods are called the reflection mechanisms of the Java language.

First, class

1, class is a class, a class describing the class (that is, the description of the class itself), encapsulates the method of describing methods, describing the field of the filed, describing the constructor of the constructor and other properties
2, objects in the mirror (reflection) can get information: The data member name of a class, method and constructor, what kind of interface is implemented by a class.
3. For each class, the JRE retains an object of the same class type.
A class object contains information about a particular class. In other words: Any class is an instance object of class
4. Class objects can only be created by the system
5, a class will have only one class instance in the JVM

Second, reflection mechanism

Reflection is a powerful tool in Java that allows us to easily create flexible code that can be assembled again at runtime without the need for source code linking between components.

Role:

    1. Determine the class to which any object belongs at run time;
    2. Gets the object of the class at run time;
    3. Accesses Java object Properties, methods, construction methods, and so on at run time.

Characteristics of Reflection:

Why use a reflection mechanism? Creating objects directly does not make sense, which involves the concept of dynamic and static.

static compilation : Determines the type at compile time, binds the object, which is passed.
Dynamic Compilation : The runtime determines the type, binding object. Dynamic compilation maximizes the flexibility of Java and embodies the application of polymorphism to reduce the coupling between classes

The advantages of the reflection mechanism: it can achieve dynamic creation of objects and compile, showing great flexibility (especially in the development of Java EE, its flexibility is very obvious). Through the reflection mechanism, we can obtain the various contents of the class, and then decompile it. For Java, which compiles and then runs the language, the reflection mechanism can make the code more flexible and easier to implement object-oriented.

Example: a large software, when the program compiled, released, will be in the late update to improve the entire program , we can not want users to uninstall the previous, and then reinstall the new version, if so, this software is certainly not many people use. Using static words, the entire program needs to be recompiled once to achieve the function of the update, and the use of reflection mechanism, it can not uninstall, only need to be dynamically created and compiled at run time, you can implement this function. Think about it, the glory of the king every time a new hero or out of the new skin will be updated, the user in the update is only to download a small package to install, instead of reinstalling the entire King Glory game, this is the use of dynamic compilation example.

The drawback of the reflection mechanism is that it has an impact on performance. Using reflection is basically an interpretation operation, and we can tell the JVM what we want to do and it satisfies our requirements. This type of operation is always slower than just performing the same operation directly.

class of implementing reflection mechanism in class

Java.lang.Class;

Java.lang.reflect.Constructor;

Java.lang.reflect.Field;

Java.lang.reflect.Method;

Java.lang.reflect.Modifier;

FourThere are three ways to get a class from the reflection mechanism

in the use of reflection gets the object of the class, The class type of the class needs to be created when the object's properties, methods, construction methods, etc.

package com.neuedu.reflect;/* * Project name: Java-reflect * @author: wzc* @date Created on: August 28, 2017 pm 8:41:29* @Description: Gets the class type of the class * @parameter * */public class JavaDemo1 {public static void main (STR        Ing[] args) {//food instance object How to represent food food1=new food ();        /* Food This class is also an instance object, class instance object * Any class is an instance object of class, three representations * The first expression---> actually tells us that any class has an implied static member class    */Class Class1=food.class;    The second representation, known as the object of the class GetClass class Class2=food1.getclass (); /* * C1,C2 indicates the class type of food class (class type) * Any class is an instance object of class classes * C1 C2 represents the class type of food, a class can only be an instance object of class */Syste    M.out.println (CLASS1==CLASS2);    The third way of expression Class class3=null; try {class3=class.forname ("Com.neuedu.reflect.Food"),} catch (ClassNotFoundException e) {//TODO auto-generated catch    Blocke.printstacktrace ();}    System.out.println (CLASS2==CLASS3); }//Create a food class Food{public void print () {System.out.println ("Hello Food");}} 

FiveCreating Objects

Getting the class type of the class allows us to create an object of that class with the class type

Package com.neuedu.reflect;/* * Project name: Java-reflect * @author: wzc* @date created: August 28, 2017 pm 8:41:29* @Description: Gets the class type of the class * @parameter * */public class JavaDemo1 {public static void main (string[] args) {//food instance object How to represent food food1=new Fo        OD ();        /* Food This class is also an instance object, class instance object * Any class is an instance object of class, three representations * The first expression---> actually tells us that any class has an implied static member class    */Class Class1=food.class;    The second representation, known as the object of the class GetClass class Class2=food1.getclass (); /* * C1,C2 indicates the class type of food class (class type) * Any class is an instance object of class classes * C1 C2 represents the class type of food, a class can only be an instance object of class */Syste    M.out.println (CLASS1==CLASS2);    The third way of expression Class class3=null; try {class3=class.forname ("Com.neuedu.reflect.Food"),} catch (ClassNotFoundException e) {//TODO auto-generated catch    Blocke.printstacktrace ();}     System.out.println (CLASS2==CLASS3);//We can create an object instance of the class through the class type of the classes try {food food2 = (food) class1.newinstance (); Food2.print (); } catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}//Create a food class Food{public void print () {System.out.println ("Hello Food");}}

Vi. getting information about a class: Class name, method name, method's return value type, method's parameter list
Package Com.neuedu.uttil;import Java.lang.reflect.constructor;import Java.lang.reflect.field;import java.lang.reflect.method;/* * Project Name: Java-reflect * @author: wzc* @date created: August 29, 2017 PM 1:22:15* @Description: 1. Use reflection to print the class's information * 2. Use reflection to print the class's member variable * 3. Using reflection to print class construction method * @parameter * */public class Uttil {/* * * Print class information, Prints the class's return value type, class class name, parameter list * * */public static void Printclass (Object obj) {class cint=obj.getclass (); System.out.println ("The name of the class:" +cint.getname ()); */* Method class, Methods Object * A member method is a Methods object * the GetMethods () method gets all the public functions, The Getdeclaredmethods (), which includes the inheritance of the parent class, gets all the methods that the class declares itself, * * */method[] ms=cint.getmethods (); System.out.println ("[Class's Return value type],[class name],[The parameter list of class]"); for (int i = 0; i < ms.length; i++) {//Gets the class type of the return value type of the method classes class ReturnType =ms[i].getreturntype (); System.out.print (Returntype.getname () + "");//Get the name of the method System.out.print (Ms[i].getname () + "(");//Get the parameter type class [] Paramtypes=ms[i].getparametertypes (); for (Class class1:paramtypes) {System.out.print (Class1.getname () + ",");} System.out. println (")");}} 

Test it:

public class Junittest {@Testpublic void Test () {string string= "Hello";//uttil.printclass (String);}}

Execution Result:

Vii. getting the properties of a class
/* member variable is also object * Java.lang.reflect.Field; * The filed class encapsulates the operation of the member variable * The GetFields () method Gets the information about the member variable of all public * Getdeclaredfields Gets the information of the member variable declared by the class itself * * * */  public static void Printfieldinfo (Object obj) {//Gets the class member variable Class Class1=obj.getclass (); Field[] Fields=class1.getdeclaredfields (); for (Field field:fields) {//Get the class type of the member variable type//Get the type name of the member variable class fieldtype= Field.gettype (); String   typename=fieldtype.getname ();//Gets the name of the member variable string   fieldname=field.getname (); System.out.println (typename+ "" +fieldname);}

Test it:

        @Testpublic void Test () {Uttil.printfieldinfo (new Integer (1));}

Results:

Viii. how to get the constructor of a class
  /*     * The constructor of the print object     * */public static void  Printconmessage (object obj) {    Class class1=obj.getclass ();    /*     constructor is also an     object * The information encapsulated in the constructor in Java.lang.Contructor     * GetConstructors gets all the public constructors     * Getdeclaredcontructors get all the constructors     *      * *      *    /constructor[] ct=class1.getconstructors ();    for (Constructor constructor:ct) {System.out.print (Constructor.getname () + "(");//Get constructor parameter list---> Get the class type of the argument list class[] Paramtypes=constructor.getparametertypes (); for (class Class2:paramtypes) {System.out.print ( Class2.getname ());} System.out.println (")");}}

Test it:

@Testpublic void Test () {String string= "Hello"; Uttil.printconmessage (string);}

Results:

Ix. methods of executing objects by reflection
Package Com.neuedu.reflect;import Java.lang.reflect.invocationtargetexception;import java.lang.reflect.Method;/* * Project Name: Java-reflect * @author: wzc* @date created: August 29, 2017 PM 6:45:21* @Description: Methods of executing classes by reflection * * @parameter * */public clas   s Runmethod {public static void main (string[] args) {Student student=new Student ("Zhang San", 25);   1. To get the method, first get the class type of the method, class Stuclass = Student.getclass (); /* * 2. Get the method, name, and argument list * GetMethod gets the public method * Getdelcaredmethod Own declaration method */try {//stuclass.getmethod ("GetName ", New class[]{})//stuclass.getmethod (" GetName "); Method M1=stuclass.getmethod ("GetName", null),//3. The reflection Operation-----Previous: Student.getname ();  M1.invoke (Obj,args.);  The reflection operation of a method is to use the M1 object to make a method call//method if no return value returns NULL, a return value returns a specific return value, and is converted to an object M1.invoke (student); System.out.println ("=============="); M1=stuclass.getmethod ("Getage", null); Object Object=m1.invoke (student, NULL); System.out.println ("=============="); M1=stuclass.getmethod ("Getage", Int.class); M1=stuclass.getmethod ("Getage", New Class[]{int.class}); M1.invoke (student, 2); } catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} Student class student{private string name;private int age;public Student () {}public Student (string Name,int age) { This.name=name;this.age=age;} Parameterless method public void GetName () {System.out.println ("name:" +name); No parameter method public void Getage () {System.out.println ("Age:" +age); Method with parameters public void getage (int num) {System.out.println (num+ "Years ago Age:" + (Age-num));} public void Studentin () {System.out.println ("Name:" +name+ ", Age:" +age);}}

Today is just a reflection of some of the most basic theory, then write some reflection of the application, only the application of a better understanding of the concept of reflection.

Java Reflection mechanism

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.