Java Reflection mechanism

Source: Internet
Author: User

Occasionally review the basic knowledge, but also known as warm and new, every time to take notes, think or send to record, write the wrong place to ask the great God to correct them.


Dynamic language, the so-called dynamic is to allow the program to modify its own structure or variable type at run time.

Java is not a dynamic language, but it provides a powerful reflection mechanism that can achieve the effect of dynamic language to some extent.

The purpose of the Java reflection mechanism is two points:

Get all the properties and methods of any class (get information dynamically) in a running state

The ability to invoke methods and properties of any object (dynamic invocation of object methods)


The reflection mechanism provides the flexibility of the runtime, as long as you know a class, you can reflect the method of creating new objects and calling objects, but while improving flexibility, the efficiency and flexibility of reflection are much less efficient than generating objects directly in code or calling methods.


Java Reflection API Basic Features

Gets the internal structure of the class, including construction methods, declared properties, defined methods, annotations, and so on, mainly through the object of the Java.lang.Class class. Here is an example of this MyClass class.

public class MyClass {private String className;    Public MyClass (String className) {this.classname = ClassName;    Public MyClass () {} public String append (string number) {return className + number; }}

Generally generate objects and Invoke methods:

MyClass MyClass = new MyClass ("Class A"); Create Object System.out.println (Myclass.append ("100")); Result: Class A100

Generate objects by reflection and Invoke methods:

As long as the object of the Java.lang.Class class, such as Myclass.class, can be obtained by reflection to obtain the constructor methods, properties and methods in the class, respectively, there are three kinds of methods:

GetConstructors ()/getconstructor ()

GetFields ()/getfield ()

GetMethods ()/getmethod ()

These three types of methods also correspond to the getdeclared*** () method, except that the latter only acquires the constructor methods, properties, and methods of the current class's own declaration, while the former gets the elements that are inherited.

Gets the constructor for the specified parameter type, such as the MyClass class has a constructor with a string parameter constructor constructor = MyClass.class.getDeclaredConstructor ( String.class);   MyClass MyClass = (MyClass) constructor.newinstance ("Class B"); Build object//Get all constructors for a class//get explicitly declared constructors, such as parameterless constructors, if not declared, will not be fetched to constructor[] constructors = MyClass.class.getDeclaredConstructors ();//Gets the method declared in the class method[] methods = MyClass.class.getDeclaredMethods (); method = MyClass.class.getDeclaredMethod ("append", String.class); System.out.println (Method.invoke (MyClass, "100")); Call method//Gets the attribute field declared in the class field[] fields = MyClass.class.getDeclaredFields (); Field field = MyClass.class.getDeclaredField ("ClassName");//array provides a reflection of the array type Object array = Array.newinstance ( String.class, 5); Array.set (array, 0, "A"); Array.set (array, 1, "B"); System.out.println (Array.get (Array, 1));


Reflection with Generics

Java5 began to introduce generics, so the Java reflection mechanism also made some adjustments to accommodate generics.

There is a signature field in the constructor and field classes that allows you to get to the generic parameter type at run time.

Gets the property field with the generic type fields field = MyClass.class.getDeclaredField ("students");//obtains the type, returns the type with the generic type if there is a generic, otherwise returns the type// The signature field of the field class is adopted to determine whether a generic//return Java.util.list<java.lang.string>type type = Field.getgenerictype (), if (type    instanceof Parameterizedtype) {System.out.println (type);    Parameterizedtype Parameterizedtype = (parameterizedtype) type;    Get parameter type type[] types = parameterizedtype.getactualtypearguments ();    for (Type t:types) {System.out.println (T.gettypename ()); }}



This article is from the "Shephenson Technology blog" blog, make sure to keep this source http://vincettse.blog.51cto.com/6578391/1719743

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.