The reflection mechanism in Java

Source: Internet
Author: User

Java Reflection mechanism
    • Reflection mechanism Definition

The reflection mechanism is a very important feature in the Java language that allows a program to self-check at run time and also allows it to manipulate internal members. Because the reflection mechanism enables the loading of classes at run time, it can increase the flexibility of the program, but using the reflection mechanism improperly can also seriously affect the performance of the system. In particular, the main functions of the reflection mechanism are: ① get the class to which an object belongs, ② gets all the member variables and methods of a class, ③ creates an object at run time, invokes the method of the object.

    • Realization of reflection mechanism

There are three ways to get classes from the reflection mechanism, and we show how to get the student class under the reflection package.

    1. Class.forName ("Path of the class") Class Student = Class.forName ("reflection.student"); Package name + class name
    2. The class name is. Class class Student = Reflection.Student.class;
    3. class instance. GetClass ()    Student Student = new Student (); Class Student = Student.getclass ();

6 Important methods in class

    1. The GetName () method returns a string string that displays the name of the class.
      • System.out.println (Student.getname ()); Output: Reflection.student
    2. The Newinstance () method, called by the class, creates an instance of the class based on the default constructor of the class
      • Object o = student.newinstance ();
    3. The getClassLoader () method returns the corresponding loader for the class object.
    4. The Getcomponenttype () method returns an array of the component types of the class, and if the class does not represent an array class, this method returns NULL.
    5. The Getsuperclass () method returns the class object corresponding to the immediate parent class for a subclass.
    6. IsArray () method to determine whether this class object corresponds to an array object.
    • Reflection mechanism gets the properties of the class (all properties and specified properties)
      • Get all Properties
 Public classTest {     Public Static voidMain (string[] args) {//Class Student = Class.forName ("reflection.student"); //Package name + class nameClass Student = Student.class; Field[] FS=Student.getdeclaredfields ();  for(Field field:fs) {System.out.print (field.getmodifiers ()+ "  ");////gets the modifier for the property, such as Public,static, and so on, with the result int typeSystem.out.print (Field.gettype (). Getsimplename () + "");//gets the name of the property typeSystem.out.println (Field.getname ()); }    }}classStudent { PublicString name; Private intID;  Public Doublescore;  Public StaticString schoolname = "Beijing University of Post and telecommunications";  Public voidPrintname () {System.out.println (name); }     Public voidSetID (intID) {         This. ID =ID; }     Public Static voidprint () {System.out.println ("This is a Student class"); }}
The output results are as follows:

1 String Name
2 int ID
1 Double Score
9 String Schoolname

      • Gets the specified property
 Public Static voidMain (string[] args) {//Class Student = Class.forName ("reflection.student"); //Package name + class nameClass Student = Student.class; Try{Field fs= Student.getdeclaredfield ("id"); Object o=student.newinstance (); Fs.setaccessible (true);//the ID property of the Student object is private, and only set to true allows property values to be directly modified externallyFs.set (O, 2018111546);        System.out.println (Fs.get (o)); } Catch(SecurityException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(nosuchfieldexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(instantiationexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(illegalaccessexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }
Output Result:
2018111546
    • Methods of obtaining classes by reflection mechanism
      • Get the constructor method of a class
        • Getdeclaredconstructors()//Get all construction methods of the class
        • Getdeclaredconstructor (parameter type. Class,......) Get a specific construction method
 Public classTest { Public Static voidMain (string[] args) {//Class Student = Class.forName ("reflection.student"); //Package name + class nameClass Student = Student.class; Constructor[] Con=student.getconstructors ();  for(Constructor C:con) System.out.println (c.tostring ());
Constructor C = student.getconstructor (String.class, Int.class, Double.class);
System.out.println (C.tostring ()); }}classStudent { PublicString name; Private intID; Public Doublescore; Public StaticString schoolname = "Beijing University of Post and telecommunications"; PublicStudent () {name= "Zhangsan"; ID= 2018111846; Score= 86; } PublicStudent (String name,intIdDoublescore) { This. Name =name; This. ID =ID; This. score =score; } Public voidPrintname () {System.out.println (name); } Public voidSetID (intID) { This. ID =ID; } Public Static voidprint () {System.out.println ("This is a Student class"); }}
Output results

Public Reflection.student ()
Public Reflection.student (java.lang.string,int,double)

Public Reflection.student (java.lang.string,int,double)

    • Get the general method of the class
      • Getdeclaredmethods()//Get all common methods
      • Getdeclaredmethod ("Method name", Parameter type. Class,......) Gets the method of the specified name
      • Getreturntype()//Gets the return type of the method
      • Getparametertypes()//Get incoming parameter type of method
 Public Static voidMain (string[] args) {//Class Student = Class.forName ("reflection.student"); //Package name + class nameClass Student = Student.class; Method[] MDS=Student.getmethods ();  for(Method m:mds) {System.out.println (M.getreturntype ()); Class[] Classs=m.getparametertypes ();  for(Class s:classs) System.out.println (S.getname ()); }} Output:voidvoidvoidintvoidvoidLongintvoidLongintclassJava.lang.ClassBooleanJava.lang.Objectclassjava.lang.Stringvoidvoid
    • 4 ways to create objects in Java
      • Instantiating an object with the new statement
      • Creating an object from a reflection mechanism
      • Create an object from the Clone () method
      • To create an object by deserializing it

The reflection mechanism in Java

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.