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.