The principle of the Java reflection mechanism and its simple application under Android

Source: Internet
Author: User
Tags comment tag

It took a few days to study the reflection mechanism of Java. Here to summarize the results of these days of learning, one to share their learning process and the problems encountered in learning, and secondly, like I do not quite understand the Java reflection mechanism of students to do a simple introduction. An app that links an android reflection mechanism later in the article.

First, the concept of reflection and class reflection in Java

Reflection refers to the ability of a program to access, detect, and modify its own state or behavior. In computer science, reflection is a class of applications that can self-describe and self-control. Such applications use a mechanism to describe and detect their behavior, and to adjust or modify the state and related semantics of the behavior described by the application according to the state and result of its behavior.

  the reflection mechanism in Java , known as Reflection . (You see this word, the first idea should be to go to the development of the document search.) It allows a running Java program to examine itself and to manipulate the internal properties or methods of the program directly. The Reflection mechanism allows the program to take advantage of Reflection apis to obtain internal information for any class with known names, including: package ,   type parameters ,   superclass ,   implemented interfaces ,   inner classes ,   outer classes ,   fields , &NBSP, Constructors ,  , methods ,  , modifiers , etc., and can be dynamically generated during the execution of Instances , change fields content, or evoke methods .

Well, knowing this, we'll know that we can use the reflection mechanism to dynamically invoke some protected or even private methods or classes in a Java program. This can largely satisfy some of our more specific needs. Of course you ask, what is the use of the reflection mechanism under the Android platform?

We are in the development of the Android program, in order to facilitate the debugging process, and quickly locate the error point of the program, will be downloaded from the Internet to the corresponding version of the Android SDK Source code (here to provide you with a 2.3.3 Version of the download link). You will find that many classes or methods often add the "@hide" comment tag, which is to make the method or class is not visible when the SDK is generated , then our program may not compile, and in the final release, there may be some problems.

So, the first way to do this is to get rid of the "@hide" tag in the Android source code , and then recompile to generate an SDK. Another approach is to use the Java reflection mechanism, which can be used to access methods that have access rights or to modify their fields.

Nonsense, it's time to get to the point, before getting to the point, give the code of the previous reflection test class, which defines the class that we need to reflect, which has no practical purpose and is used only as a test class. Hint: This article provides the code, not the Android platform code, but a common Java program, just the Java Reflection mechanism of the Demo program, so we do not put in Android under the compilation Ah, otherwise there is a problem, do not hold my responsibility!

Reflectiontest.java 

Second, the reflection mechanism needs to use the class

The classes I need to use are listed in the following table, where classes that are particularly useful to us are shown by highlighting them and will be explained incrementally in later use:

Third, class

The first thing to tell you is that class itself is a class, and class is the name of that class. Look at the following definition of this class:

public class MyButton extends Button {...}

Notice that the first letter of the class above is lowercase, it represents a class type, but our class is a class, equivalent to the MyButton class defined above . Therefore, do not take the class here as a type to understand. Understand this, we continue.

Class is the source of the entire Java Reflection mechanism, and the class class itself represents the type of Java object, which we can pass through the object 's The GetClass () method gets the type of an object that the function returns as a class . There are a number of ways to get Class objects:

In peacetime use, should pay attention to these several methods of flexible use, especially to the Class.forName () method of use. Because in many developments, objects of class classes are obtained directly from the name of the classes .

Iv. Obtaining information about the class

1. Get the Construction method

The class class provides four public methods for getting a class's construction method.

Constructor GetConstructor (class[] params) returns a concrete constructor with the public property , based on the parameters of the constructor

Constructor GetConstructors () returns all constructor arrays with the public property

Constructor getdeclaredconstructor (class[] params) returns a concrete constructor (without public and non-public attributes), based on the arguments of the constructor function

Constructor getdeclaredconstructors () returns all the constructor arrays in the class (without public and non-public properties)

Since the Java language is an object-oriented language with polymorphic properties, we can invoke different constructor methods to create an instance of the class by constructing the parameter list of the method. Similarly, to obtain information about the different construction methods, you also need to provide the corresponding parameter type information, therefore, there are four different ways to get the construction method.

get_reflection_constructors ()

2. Get the Member method of the class

There are four ways to get member methods in the same way that you get a constructor method.

Method GetMethod (String name, class[] params) returns a concrete way with the public property , based on the method name and arguments

Method[] GetMethods () returns all array of methods with the public property

Method Getdeclaredmethod (String name, class[] params) returns a specific method (without public and non-public attributes) based on the method name and arguments

Method[] Getdeclaredmethods () returns all the method arrays in the class (without public and non-public properties)

Get_reflection_method ()

When you get the member method of a class, there is one place that deserves attention, namely the GetMethods () method and the Getdeclaredmethods () method.

GetMethods (): A member method used to get all the public-decorated fields of a class , including the public method inherited from the parent class and the public method that implements the interface ;

Getdeclaredmethods (): An interface method used to get all the member methods and implementations defined in the current class, excluding methods inherited from the parent class.

You can check the explanation of the development documentation:

GetMethods ()-Returns An array containing Method objects for all public methods for the class C represented by this class .

Methods May is declared in C, the interfaces it implements or in the superclasses of C.

The elements in the returned array is in no particular order.

Getdeclaredmethods ()-Returns a Method object which represents the method matching the specified name and parameter types

That's declared by the class represented by this class.

So in the sample code the method Get_reflection_method (...) , the Reflectiontest class inherits the Object class, implements the actionperformed method, and defines the following member methods:

The results are different after the two statements are executed:

A, method[] methods = Temp.getdeclaredmethods () After execution results as follows:

    

b, method[] methods = Temp.getmethods () after execution, the result is as follows:

     

3. Gets the member variable (member property) of the class

There are four ways to get member properties

Field GetField (String name) returns a specific member variable with the public property, based on the variable name

Field[] GetFields () returns an array of member variables with the public property

Field Getdeclaredfield (String name) returns a member variable (without public and non-public attributes) based on the variable name

Field[] Getdelcaredfield () returns an array of all member variables (without public and non- public properties)

Get_reflection_field_value ()

4. Get the decorated fields of class, property, method

Class , Method,Constructor,Field all have a public method int getmodifiers (). The method returns a number of type int that represents the decorated object ( Class, Method, Constructor, Field ) The combined value of the decorated type.

In the development documentation, you can see that theModifier class defines a number of specific decorated fields, each of which is a fixed int value, as the following list:

    

This class not only provides a number of methods to determine whether a modified domain is owned by boolean isxxxxx (int modifiers), but also provides a String toString (int modifier) method. Used to convert an int number that represents a combined value of a decorated field to a string that describes the decorated field.

    

V. How to invoke private methods in a class

Before the introduction, put a code, this code is to refer to the code of other articles copied over, the code is not long, but the dynamic invocation of the class member method of the process is easy to understand.

Loadmethod.java

To invoke a method of a class, you first need an instance of that class (of course, if the class is static, you do not need an instance, as for the reason, you know!) )。

1. Create an instance of a class

After we get the class object of a kind , we can instantiate the object with the class Constructor. Constructor supports generics, that is, it should be constructor<t> itself. This class has a public member function:T newinstance (Object ... args), where args is the corresponding parameter, we pass Constructor This method to create an object instance of the class.

In code Loadmethod.java and Loadmethodex.java , two methods for instantiating class classes are given: one is the use of Constructor class calls the Newinstance () method, and the other is to Create an instance using the Newinstance () method of the class itself. The two methods achieve the same effect.

Use the Newinstance () method to obtain an instance of a construction method

Class's Newinstance method, which provides only the default, non-parametric instantiation method, similar to an argument-free construction method

The Newinstance method of constructor provides an instantiation method with parameters, similar to the construction method with the parameter

Constructor ct = cls.getconstructor (null);

Object obj = ct.newinstance (null);

Object obj = cls.newinstance ();

2. Behavior

The method class contains information about the member methods of the class. There is a public member function in the Method class :object Invoke (Object Receiver, object ... args), parameter receiver Indicates the calling object, and the parameter args indicates the parameters that the method needs to receive. Since we are dynamically invoking a method of a class at run time, we cannot know in advance the type of the class's parameter and return value, so the type of the passed parameter is object, and the type returned is object. (Because the Object class is the parent class of all other classes)

If a method is a static method of a Java class, then the object receiver parameter can pass in NULL because the static method never belongs to the object.

3. Properties

To read and write the member variables of a class, There are two public methods in the Field class:

Object get (Object object), which can be used to get the value of a member variable

Void set (Object object, Object value), which sets the value of a member variable

Where the object parameter is required to be passed in, and if the member variable is a static property, an object can pass null.

Six, the optimization of the treatment of Loadmethod.java

In the Loadmethod.java given in the previous section , the class Loadmethod calls the method of the fixed parameter type, and the parameter type is passed in through a string[] array, and then through the method Getmethodtypesclass () after parsing, the specific type of the parameter is obtained. Also in the Getmethodtypesclass () and Getmethodparamobject () methods, the parameter types that can be matched are processed by filtering the passed-in string parameters. Other parameters that cannot be matched are handled as String objects. What should we do if we call a method that requires a parameter that is not a simple type of variable, but a custom class object, or a list of lists, and if we only know the class name and method name and do not know the parameter type of the method?

Therefore, I have done some optimization to the Loadmethod class. Attach the code First:

Loadmethodex.java 

We pass a series of analyses in the previous sections, so long as we know the class name of a class (including the path to its package), we can get the class's member variables, constructor methods, member methods, and the parameter types and return types of the member methods through a series of methods in class. There are also information such as modifier fields.

If we already know a class name and the method name that needs to be called dynamically, how can we call the method without passing in the parameter type of the method?

In the case of a known class name, we can print out all the information of the class, including the class's Member method, and then filter the method name of the printout by the given method name, find out the method we need, and then, through the method object, get the parameter type of the method, The number of parameters, and the return type. So when we call this method externally, we don't need to be concerned about the type of parameter that the class needs to pass in, just passing in the class name, method name, parameter value information. The author realizes a class Loadmethodex, and first makes a comparison between the parameters required by the same method of the two classes:

    

    

1, Loadmethodex class, one less parameter (method parameter type list), this article directly from the class Loadmethod internal Get the parameter type list, do not need the user to pass this information, the benefit actually also self-evident.

2, the parameter value of the method: Class Loadmethod is all the method parameters are passed as a String to pass in, and then parse, and this article is directly using the Object type as the parameter type, because The parameter type required by the invoke (object obj, Object...args) method itself is Object, which avoids unnecessaryparameter type transformations.

When calling the Loadmethod load () method, the user only needs to know the class name, the method name, and the initialized parameter is first converted to Object, and then passed to the load () method. The return value of the method is Object, which is definitely the type that the user needs to convert to himself.

Execution Results

Vii. Summary

In fact, there is a more sensitive topic in the reflection mechanism, that is, the reflection mechanism brings us security problems. As I am not very thorough in this field, I cannot speak well. You can keep track of the two links provided at the end of this article, there are some introductions.

We have introduced the reflection mechanism of Java, but under the Android platform, is there any use of the reflection mechanism specifically? The answer is yes. We recommend that you read an article, "Using Java Reflection Technology to stop the dialog box through a button," This article is recommended for CSDN as a boutique article, so it is worth a look. I have specially reproduced from CSDN for everyone to study together.

 

Original link: http://blog.csdn.net/nokiaguy/archive/2010/07/27/5770263.aspx

Reprint Link: http://www.cnblogs.com/crazypebble/archive/2011/04/13/2014297.html

Program implementation of the source code:

androidreflection

Mybuttonhandler.java

After reading the above article, I want you to make it clear that the reflection mechanism can get the private methods and properties of a class using the void Setaccessible (Boolean flag) method and use these Private methods and properties have been able to do something beyond the limits. So in the use of the process, but also need to be cautious ah!

Each step of the code is explained in detail, but due to too many comments, there may be some obstacles to reading, please understand. At the same time, this article mainly refer to two articles:

1, http://zlb1986.iteye.com/blog/937781

2, http://www.cnblogs.com/keis/archive/2011/03/29/1998736.html

Thanks to the two-bit article for this article provides a certain basis for me to learn Java Reflection mechanism provides a good tutorial. This article is also a study summary, if this article on the author of the two articles have offended, please contact me in time. If you find this article and the code error, please correct me, learn to communicate together.

Attached: Two works for everyone to study together. Http://u.115.com/file/f68453a0ca

Turn from:

Crazy Pebbles: http://www.cnblogs.com/crazypebble/archive/2011/04/13/2014582.html

The principle of the Java reflection mechanism and its simple application under Android

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.