Java Reflection Mechanism Series (i) Primary Java Reflection

Source: Internet
Author: User

Java reflection mechanism refers to the Java program can be loaded during the execution period, to detect, using the compile period is completely unknown classes. This sentence may be a bit difficult to understand, we can look at an example. In Java programs we often use such a statement to create an object. Date date = new Date (); The type of date in this statement (Java.util.Date) is determined at compile time. So, there is no way to make the object type of the time from the compile to run, the answer is yes. This is the convenience provided by the Java reflection mechanism. And it can not only generate objects but also get field, set values for the field, and invoke methods.

When it comes to Java reflection, it's important to know a class called "class," which is the basis of the Java reflection mechanism. "Class", like other classes, inherits from the object class, and its instance object is used to describe a type, interface, or primitive type (such as int) of the Java runtime. Class "is created by the JVM and does not have a common construction method. Let's take a look at how to get the "class" class instance.

There are mainly three ways.

Forname is obtained by static method of class classes. Class CLA = Class.forName ("java.lang.String");

Two, through. The type or. Class property is obtained. Class CLA = String.class; Class cla1 = Int. Type;

Third, obtains by the GetClass method of the instance variable. String s = ""; Class CLA = S.getclass ();

The instance object, as shown above, is a description of the string type, through which we can create a string instance and invoke the methods therein. Next I'll show you how to use the Java reflection mechanism with an example.

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.