Java Reflection mechanism

Source: Internet
Author: User

The most important part of the reflection mechanism is allowing you to examine the structure of the class. The three classes in the Java.lang.reflect package field, method, and constructor describe a class's fields, methods, and constructors accordingly. The following steps must be followed when using these classes:

The first step is to get the Java.lang.Class object of the class you want to manipulate. Here is one way to get a class object: Class C = Class.forName ("java.lang.String"); This statement gets the class object of a String class. There is another way: Class C = int.class; or Class C = Integer.type; Basic types of class information are available.

The second step is to call a method such as Getdeclaredmethods to get a list of all the methods defined in the class.

Method m[] = C.getdeclaredmethods ();

System.out.println (M[0].tostring ()); Prints the prototype of the first method defined in String as text.

The role of Class.forName? Why do you use it?

A: Class is a running class, and forname (className) loads the class named ClassName into the JVM, so that classes can be loaded dynamically, and some of this information can be obtained through the reflection mechanism of class. The role of Class.forName dynamically loads and creates Class objects.

The class loader is used to load the. class file, reading the bytecode of the. class file and loading it into memory.

About initialization of classes (execution of static program segments):

1, a A = new A ();//initialization when class is loaded

2, Class.forName (A);//initialization when class is loaded (loading class)

3, Class.forName (A,false,classloader);//initialization at newinstance

4, Classloader.loadclass (A);//initialization at newinstance

Static block executes only once

(1) using Class.forName ()

+-public static Class forname (String className)

+-public static Class forname (String className, Boolean initialize,classloader loader)

Parameter description:

ClassName-Fully qualified name of the desired class (including full path)

Initialize-whether the class must be initialized (initialization of static code blocks)

Loader-Class loader for loading classes

Whether you are using new to instantiate a class, or use the Class.forName () method with only one parameter, the procedure for "load class + run static code block" is implied internally. When using the Class.forName () method with three parameters, if the second argument is false, the class loader only loads the class without initializing the static code block, and the static code block is initialized only when the class is instantiated. A static block of code is initialized when the class is instantiated for the first time.

Class classes and objects

A class is part of a program, and each class has an object of class. In other words, each time a new class is written, a class object is also created (more appropriately, in a. class file with exactly the same name). At run time, once we want to generate the object of this class, the Java Virtual Machine (JVM) running the program first checks to see if the class object is already loaded. If it is not already loaded, the JVM will look up the. class file based on the class name and load it. So Java programs are not completely loaded from the start, unlike many traditional languages.

Once a class object is loaded into memory, it is used to create all objects of the class. Note: Class objects are loaded only when they are needed. There is no public construction method for class classes. Class objects are constructed automatically by the Java virtual machine when the class is loaded and by invoking the DefineClass method in the ClassLoader, so you cannot explicitly declare a class object.

The basic Java types (Boolean, Byte, char, short, int, long, float, and double) and the keyword void also correspond to a Class object. Each array belongs to a class that is mapped to a class object, and all arrays that have the same element type and number of dimensions share the class object.

There are three ways to get objects of class:

1. Call the GetClass () method of the object class to get the class object. For example:

MyObject x; Class C1 = X.getclass ();

2. Use the class class's Static Forname () method to get the class object corresponding to the string. For example:

Class C2=class.forname ("MyObject");//myobject must be the name of the interface or class.

3. If T is a Java type, then T.class represents the matching class object. For example

Class CL1 = Manager.class;    Class Cl2 = Int.class; Class Cl3 = Double[].class;

Note: The class object actually describes only the type, and this type is not necessarily a class or interface. For example, the above int.class is an object of type class.

Ii. Common methods of class

1, GetName () returns the name of the entity (class, interface, array class, base type, or void) represented by this class object as a String.

2, newinstance () create an instance for the class. For example: X.getclass.newinstance (). The Newinstance () method invokes the default constructor (no parameter constructor) to initialize the new object.

3, getClassLoader () returns the class loader for this class.

4, Getsuperclass () returns the class of the superclass that represents the entity represented by this class.

5, IsArray () determines whether this class object represents an array class.

Third, some of the use of class skills

1. forname and newinstance are used together to create an object based on the class name stored in the string. For example, Object obj = Class.forName (s). newinstance ();

2. The virtual machine manages a unique class object for each type. You can therefore use the = = operator to compare class objects. For example: if (e.getclass () = = Employee.class) ...

Java ClassLoader principle

Java ClassLoader is an important Java Runtime system component. It is responsible for locating and loading classes of class files at run time. The class loader is used to load classes (class) into the JVM. The JVM specification defines two types of class loaders: the boot Inside loader (bootstrap) and the user custom loader.
Bootstrap is the class loader that the JVM comes with to load the core class libraries, such as java.lang.*. The Java.lang.Object is loaded by bootstrap. Java provides an abstract class ClassLoader, where all user-defined class loaders instantiate subclasses from ClassLoader.

The System class Loader is a special user-defined class loader, provided by the JVM's implementation, which loads the user class by default when the programmer does not specifically specify the loader. The System class loader can be obtained by means of the Classloader.getsystemclassloader () method.
class loader to load a class into a Java virtual machine, to go through three steps: Load, link and initialization, where the link can be divided into the verification, preparation and parsing three steps, in addition to parsing, the other steps are strictly in order to complete, the main work of each step is as follows:
(1) Load: Look for a class or a binary form of an interface and use that binary form to construct the process that represents the class or this interface's class object.

(2) Link: The class type data is merged into the JVM run-time state. Perform calibration, preparation and resolution steps;

Checksum: Check the correctness of binary data of imported class or interface; Prepare: Assign and initialize storage space for static variables of class; parse: Convert symbol reference to direct reference;

(3) Initialize: Initialize Java code and static Java code block. Initialization occurs the first time the JVM actively uses the type. The so-called active use includes the following situations:
[1] When a new instance of the class is created (the new directive or by ambiguous creation, reflection, cloning, or deserialization)
[2] When invoking a static method of a class
[3] When a static field is used for a class, or when the field is assigned a value (except for the final decorated static field)
[4] When initializing a subclass of a class
[5] A class that is marked as a startup class when the JVM starts and that contains the main () method

The class object of an array class is not created by the type loader, but is created automatically by the Java runtime as needed. The class loader for an array class is returned by Class.getclassloader (), which is the same as the class loader of its element type, and if the element type is a base type, the array class does not have a class loader.

Ways to load classes on virtual machines:

1, dog dog = new Dog ();

2, Class clazz = Class.forName ("Dog");

Object dog =clazz.newinstance ();

3, Class clazz = Classloader.loadclass ("Dog");

Object dog =clazz.newinstance ();

So what is the difference between 1 and 2 and 3? What are the conditions for each?

The class loaders used by 1 and 2 are the same and are the current class loaders. (ie: this.getClass.getClassLoader).

3 The class loader is specified by the user. If you need to look for a class outside of the current classpath, you can only use the 3rd way. The 3rd way the class is loaded is a different namespace from the current class.

In addition, the 1th and 2nd will result in static initialization statements for the class, and the 3rd case will not. Another 1th throws the error, the 2nd, 3 throws exception, they belong to different exception/fault branches.

Citation: http://blog.csdn.net/yakihappy/article/details/3979369

Java Reflection mechanism

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.