Java Reflection mechanism

Source: Internet
Author: User

Java Reflection mechanism

Person P=new person ();
What is this? Of course, an object is instantiated. However, there is a problem with the method of instantiating an object, that is, it is necessary to know the class name to instantiate its object, so that we are constrained in our application. So is there a way to instantiate its object without knowing the class name of the class? Thank goodness! Fortunately we use Java, Java provides such a mechanism.


1). Java programs can obtain bytecode information for any class at run time, including class modifiers (public,static, etc.), base class (superclass, parent class), interfaces implemented, fields and methods, and so on.
2). Java programs can create instance objects of the class based on bytecode information at run time, altering the object's field contents and calling object methods.
This mechanism is called reflection technology. You can imagine the reflection in optics, just as we look in the mirror, and there's another one in the mirrors (the analogy may not be appropriate, but it's enough to express it clearly). Reflection technology provides a common method of dynamically connecting program components without having to hardcode the target class required by the program into the source program, allowing us to create flexible programs.


The reflection mechanism of Java is implemented through the Reflection API, which allows the program to obtain internal information for any class of known name during the run. The Reflection API is located in the Java.lang.reflect package. The main categories include the following:
1). Constructor class: A method used to describe the construction of a class
2). Field class: A member variable used to describe a class
3). Method class: A way to describe a class.
4). Modifer class: Modifiers used to describe elements within a class
5). Array: Used to manipulate the array.
Constructor,field,method These three classes are created by the JVM (virtual machine) when the program is run, to represent the corresponding members in the Load class. All three classes implement the Java.lang.reflect.Member interface. The member interface defines methods for obtaining information such as class members or construction methods. To use these reflection APIs, you must first get an instance of the class class of the object or class that you want to manipulate. By calling the class's Newinstance method (only the default constructor method for classes can be called) You can create an instance of a class. This has limitations, we can first get the class instance of the class to obtain the constructor method, and then use reflection to create an instance of the class.


I. Get the constructor object (array) of the constructor method of the class
constructor[] Getdeclaredconstructors (); Returns an array of Constructor objects for all constructed methods declared by the loaded class.
Constructor getdeclaredconstructor (class[] paramtypes); Returns the Constructor object of the specified constructed method declared by the loaded class, paramtypes specifies the parameter type.
constructor[] GetConstructors (); Returns an array of Constructor objects for the constructor of all public types declared by the loaded class.
Constructor getconstructor (class[] paramtypes); Returns the Constructor object of the constructor method of the specified public type declared by the loaded class, paramtypes specifies the parameter type.
if a constructor is not defined in a class, the first and third methods return an array with only one element, which is the default constructor, and if a class has only a constructor with parameters defined, and no default constructor is defined, the first and third methods return an array that does not contain the default constructor method.

two. Gets the class member variable of the Field object (array)
field[] Getdeclaredfields (): Returns an array of Field objects for all member variables declared by the loaded class, not including member variables inherited from the parent class.
Field Getdeclaredfield ( String name): Returns the Field object of all member variables declared by the loaded class, excluding member variables inherited from the parent class, the name of the member variable specified by the parameter name.
field[] GetFields (): Returns an array of Field objects for all public-type member variables that have been declared by the loaded class, including member variables inherited from the parent class
Field GetField (String name): Returns the Field object of all member variables for the loaded class declaration, including the member variable inherited from the parent class, the name of the member variable specified by the parameter name.

three. Method Object (array) that gets the methods of the class
method[] Getdeclaredmethods (): Returns an array of method objects for all methods declared by the loaded class, not including methods inherited from the parent class.
Method Getdeclaredmethod (String name,class[] paramtypes): Returns the method object for all methods declared by the loaded class, excluding methods inherited from the parent class, the name of the specified method, and the parameter type of the method specified by the parameter paramtypes.
method[] GetMethods (): Returns an array of method objects for all methods declared by the loaded class, including methods inherited from the parent class.
Method GetMethod (String Name,class[] Paramtypes: Returns the method object for all methods declared by the loaded class, including the method inherited from the parent class, the name of the specified method, and the parameter type of the parameter paramtypes the specified method.


Four. Retrieving additional information about a class
int getmodifiers (): Returns the Shaping identity value of the modifier for the loaded class.
Package Getpackage (): Returns the packages name of the loaded class
Class Getsuperclass (): Returns a class instance of the parent class of the loaded class.
class [] Getinterfaces (): Returns an array of class objects for the interfaces implemented by the loaded class.
Boolean isinterface (): Returns whether the loaded class is an interface.
The function of reflection is very powerful, but improper use may have disadvantages greater than the advantages, reflection makes the code logic confusion, will bring maintenance problems.

Note:

Runtime type recognition (run-time type identification, RTTI) has two main ways, one is that we know all types at compile time and run time, and the other is a powerful "reflection" mechanism.

To understand how Rtti works in Java, you must first know how the type information is represented at run time, which is done by the "class object", which contains information about the class. Classes are an important part of a program, each class has a class object, and whenever a new class is written and compiled, a class object is created, which is stored in a. class file of the same name. At run time, when we want to generate objects of this class, the Java Virtual Machine (JVM) running the program confirms that the class object is loaded, and if it is not already loaded, The JVM will look up the. class file based on the class name and load it, and once the class object is loaded into memory, it is used to create all the objects of the class. The general form of Rtti consists of three types:

1. Traditional type conversion. such as "(Apple) Fruit", by Rtti to ensure the correctness of the type conversion, if a wrong type conversion is performed, a ClassCastException exception is thrown.

2. Use the class object to get the type of the object. Such as

Class C = class.forname ("Apple");

Object o = c.newinstance ();

3. Use the keyword instanceof or class.isinstance () method to determine whether an object belongs to an instance of a particular type, and, to be exact, should be instanceof/class.isinstance () Can be used to determine whether an object belongs to an instance of a particular class and all of its base classes, unlike equals ()/=, which are used to compare whether two objects belong to an instance of the same class and do not consider an inheritance relationship.

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.