A brief introduction to the reflection mechanism of Java

Source: Internet
Author: User

The reflection mechanism is a very important feature in the Java language, which allows programs to self-check at run time, and also allows internal members to operate. Although this feature is not used much in real-world development, languages such as Pascal, C, and C + + do not provide such a feature at all. Because the reflection mechanism enables the loading of classes at run time, the flexibility of the program can be increased, but improper use of the reflection mechanism can also severely affect the performance of the system.

Specifically, the reflection mechanism provides the following features:

1. Get the class to which an object belongs;

2. Get all the member variables and methods of a class;

3. Create objects at run time;

4. The method of invoking the object at run time.

In fact, one of the most important functions of the reflection mechanism is the ability to dynamically create objects of the class at run time, as in the following example:

1 package cn.ch4;   2     3 class base{   4 public     void F () {   5         System.out.println ("Base");   6     }   7}   8 class Te extends base{   9 public     void F () {         System.out.println ("Te");  One} of the public  class Fanshetest {+  public     static void Main (string[] args) {  15         try{//uses the reflection mechanism to load class             c = class.forname ("cn.ch4.Te");//Note that this is the full path including the  package             Base B = ( Base) c.newinstance ();             B.f ();         }catch (Exception e) {             e.printstacktrace ();  +         }  23}  

The result of the operation is TE.

In reflection, class is a very important class, and there are three main ways to get the class you want:

1>class.forname ("Path of the Class"), as in the example above;

2> class name. Classes;

3> instance. GetClass ().

A brief introduction to the reflection mechanism of 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.