The reflection of the Java series

Source: Internet
Author: User
Tags modifier

What is reflection

The reflection mechanism allows the class information loaded by the JVM to be obtained in Java code, such as member variables, methods, constructors, and so on.
The relevant tool classes and interfaces for getting class and object reflection information are provided under Java package Java.lang.reflect, such as: Field,method,constructor

What you can do with reflection

Reflection is often used in programming that requires checking or modifying the run-time behavior of the application, which is a very useful technique.
Specifically, the reflection mechanism can be used in the following scenarios:

    • Feature extension, an application can create an instance of a class with a fully qualified name by reflection, thereby using an external user-defined class.
    • Browsing the class information in a visual development environment, in fact, the class information displayed through shortcut keys in Eclipse Ctrl + O is implemented using the reflection mechanism.
    • For program debuggers and test tools
Disadvantages of Reflection

Although the reflection mechanism can enhance the functionality and usage scenarios of the application, it is not suitable for use in all circumstances, because the reflection mechanism itself has some inherent drawbacks.

    1. Performance loss, reflection requires dynamic resolution of types, and there is a performance loss in cases where reflection is not used, so do not use reflection in applications that are more sensitive or important to performance.
    2. Security restrictions, which reflect the need for run-time permissions under Security Manager (SecurityManager) are prohibited, than in applet programs.
    3. The class structure is exposed, and because reflection allows some illegal operations to be performed in non-reflective code, breaking Java's original abstract model may affect the behavior and escalation of the platform.
Application Practice
/*** Use the reflection mechanism to get the class information loaded by the JVM and instantiate the class object. * @desc Org.chench.test.java.UserReflector * @author[email protected]* @date November 30, 2017 */ Public classUserreflector { Public Static void Main(string[] args)throwsException {String ClassName ="Org.chench.test.java.User";//Get its class object by the full qualified name of the classclass<?> userclass = Class.forname(ClassName);//Use the reflection mechanism to get a list of constructors for a classconstructor[] Constructorarr = userclass.GetConstructors(); for(Constructor Constructor:constructorarr) {//The name of the constructorString name = constructor.GetName(); System. out.println("constructor Name:"+ name);the number of arguments to the//constructor            intCount = constructor.GetParameterCount(); System. out.println("Constructor parameter count:"+ count);parameter list of the//constructorparameter[] Parameters = constructor.GetParameters(); for(Parameter parameter:parameters) {//Get parameter typeclass<?> parametertype = parameter.GetType();//Get parameter nameString parametername = parameter.GetName(); System. out.println(ParameterName +"Type:"+ ParameterType); }//Instantiate class object by constructor function            if(Count <=0) {User user = (user) constructor.newinstance(); System. out.println("User instance:"+ user); }Else if(Count = =1) {User user = (user) constructor.newinstance(NewObject[] {"Zhang San"}); System. out.println("User instance:"+ user); }Else if(Count = =2) {User user = (user) constructor.newinstance(NewObject[] {"Li Si", -}); System. out.println("User instance:"+ user); } System. out.println("----------"); }//Use the reflection mechanism to get the member variables of a classfield[] fields = userclass.Getdeclaredfields(); for(Field field:fields) {//Variable typeclass<?> fieldtype = field.GetType();//variable nameString fieldName = field.GetName();//variable modifier, private:2,public:1, Protected:4, default type: 0            intFieldModifier = field.getmodifiers(); System. out.println("Field info, Name:"+ FieldName +", type:"+ FieldType +", modifier:"+ FieldModifier); }//methods to get classes using the reflection mechanismMethod[] methods = UserClass.Getdeclaredmethods(); for(Method method:methods) {//Method return value typeClass<?> ReturnType = method.Getreturntype();//Method nameString MethodName = method.GetName();//Method parameter number            intCount = method.GetParameterCount(); System. out.println("Method info, Name:"+ MethodName +", return type:"+ ReturnType +", Parameter count:"+count); }    }}

In fact, the scenario in which the most reflective mechanisms are used in application programming is mainly in the following 2 areas:

    1. Gets the annotation information for a class, method, or member variable in the annotation parser by reflection.
    2. Method execution is invoked using the reflection mechanism in the dynamic proxy class.

Reference
Https://docs.oracle.com/javase/tutorial/reflect/TOC.html

The reflection of the Java series

Related Article

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.