Java Reflection mechanism: includes components, structures, and sample descriptions

Source: Internet
Author: User
Tags constructor inheritance variables reflection static class

Introduction to the 1th part of Java reflection mechanism

Java reflection mechanism. Generally speaking, in the running state, we can restore "all the information of the class" according to "the information of the part of the class". Here "the part of the class already information" can be "class name" or "Object of class" and other information. "All information about a class" means "class properties, methods, inheritance relationships, and annotation annotations."

To give a simple example: Suppose for Class Reflectiontest.java, the only information we know is that its class name is "Com.skywang.Reflection". At this point, we want to know other information about Reflectiontest.java (such as its constructor, its member variables, and so on), what to do?
This requires the use of "reflection." Through reflection, we can parse out the complete information of Reflectiontest.java, including its constructors, member variables, inheritance relationships, and so on.

After you understand the concept of the Java reflection mechanism, consider a question: how do you get the complete information of a class based on the class name of the class?

This process is mainly divided into two steps:
The 1th step: According to "class name" to get the corresponding class object.
2nd Step: Through the Class object function interface, to read "class constructors, member variables" and other information.
Below, we will deepen our understanding of this concept based on the example. Examples are as follows (Demo1.java):

Package com.skywang.test;
     
Import Java.lang.Class;
     
public class Demo1 {public
     
    static void Main (string[] args) {
     
        try {
            //The corresponding class object is obtained based on the class name
            class<?> CLS = Class.forName ("Com.skywang.test.Person");
     
            Creates a new object. Newinstance () invokes a constructor with a class without arguments
            Object obj = cls.newinstance ();
     
            System.out.println ("cls=" +cls);
        } catch (Exception e) {
            e.printstacktrace ();
     
}}} Class Person {public Person
    () {
        System.out.println (' Create person ');
    }
}

Run Result:
Create person
Cls=class Com.skywang.test.Person

Description
The full package name of the person class is "Com.skywang.test.Person". and Class.forName ("Com.skywang.test.Person"); The function of this sentence is to get the person's class object according to the package name.
(02) Next, we call the Newinstance () method of the class object and create the person object.

Now we know the concept of the "Java Reflection mechanism" and how it works. With this overall idea, we can then begin to delve into the reflection.

Part 2nd Class Detailed description

1 methods to get class objects

Here's a summary of 4 common ways to get class objects:
Method 1:class.forname ("Class name string") (Note: Class name string must be full name, package name + class name)
Method 2: Class name. class
Method 3: Instance object. GetClass ()
Method 4: "Class name string". GetClass ()

Below, we demonstrate these 4 methods by example. Examples are as follows (Demo2.java):

Package com.skywang.test;
     
Import Java.lang.Class; public class Demo2 {public static void main (string[] args) {try {//method 1:class.forna
            Me ("Class name string") (Note: Class name string must be full name, package name + class name)//class CLS1 = Class.forName ("Com.skywang.test.Person");
            class<?> cls1 = Class.forName ("Com.skywang.test.Person");
     
            class<person> cls1 = Class.forName ("Com.skywang.test.Person"); 
     
            Method 2: Class name. class Class cls2 = Person.class;
            Method 3: Instance object. getclass () person person = new person ();
     
            Class CLS3 = Person.getclass (); 
            Method 4: "Class name string". GetClass () string str = "Com.skywang.test.Person";
     
            Class CLS4 = Str.getclass ();
     
        System.out.printf ("cls1=%s, cls2=%s, cls3=%s, cls4=%s\n", CLS1, Cls2, CLS3, CLS4);
        catch (Exception e) {e.printstacktrace ();
  }} class Person {  Public person () {System.out.println (' create person '); }
}

Run Result:

Create person
Cls1=class Com.skywang.test.Person, Cls2=class Com.skywang.test.Person, Cls3=class Com.skywang.test.Person, cls4= Class Java.lang.String

2 Class API description

The full API for class is the following table:

Class has the following table: public static Class forname (string className) public static class forname (string name, Boolean init Ialize, ClassLoader Loader) public constructor GetConstructor (class[] parametertypes) public constructor[] Getconstr Uctors () public constructor Getdeclaredconstructor (class[] parametertypes) public constructor[] Getdeclaredconstruct ORS () public constructor Getenclosingconstructor () public method GetMethod (String name, class[] parametertypes) Publ IC method[] GetMethods () public method Getdeclaredmethod (String name, class[] parametertypes) public method[] Get Declaredmethods () public mode Getenclosingmethod () public Field GetField (String name) public field[] GetFields ( Public Field Getdeclaredfield (String name) public field[] Getdeclaredfields () public type[] Getgenericinterface S () public Type getgenericsuperclass () public annotation<a> getannotation (Class annotationclass) public Annota Tion[] Getannotations() public annotation[] Getdeclaredannotations () public boolean isannotation () public boolean isannotationpresent ( Class annotationclass) Public boolean Isanonymousclass () public boolean IsArray () public boolean IsAssignableFrom (Class CLS) public boolean desiredassertionstatus () public class<u> Assubclass (class clazz) public Class ge Tsuperclass () public class Getcomponenttype () public class Getdeclaringclass () public class Getenclosingclass () p Ublic class[] getclasses () public class[] getdeclaredclasses () public class[] Getinterfaces () public Boolean I Senum () Public boolean isinstance (Object obj) public boolean isinterface () public boolean islocalclass () public b 
Oolean Ismemberclass () public boolean isprimitive () public boolean issynthetic () public String getsimplename () public string GetName () public string Getcanonicalname () public string toString () public ClassLoader GetClass Loader () Public Package   Getpackage () public int getmodifiers () public protectiondomain getprotectiondomain () public URL getresource (St Ring name Public InputStream getresourceasstream (String name) public object cast (object obj) public object Newin Stance () public object[] Getsigners () public object[] getenumconstants () public typevariable[] Gettypeparameters ( )

Based on the characteristics of classes, we describe classes in 4 parts: constructors, member methods, member variables, and other information about the class (such as annotations, package names, class names, inheritance relationships, and so on). Class involves annotation (annotation) related APIs, you can click to see the previous chapter on the annotation details.

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.