Analysis of Java reflection mechanism + application examples

Source: Internet
Author: User
Tags object object

Analysis of Java reflection mechanism + application examples

--Reprint Please specify Source: Coder-pig


Introduction to this section:


In fact, a long time ago, I wanted to generalize about this reflection mechanism in Java, a few days ago, I saw a reflection mechanism of the network

Video tutorials Feel good, and review a bit, today interview for an afternoon, come back don't want to write code, write about Java

A summary of the reflection, write some simple examples of use, and finally found 2 examples of application of the reflection mechanism in Android, respectively, is

The older SDK uses the Aidl + Java reflection mechanism to answer and hang up the phone and use the reflection mechanism to close it via a button

dialog box, follow-up if used to the other summary ~




The text of this section:

1. Reflection of the relevant concept map:




2. Simple Use Example:

We write a simple example to understand the use of the Java reflection mechanism, in fact, through the class of related methods to implement it!

Let's start by defining a class to do a demonstration: Test.java:

Package Com.jay.test;public class Test {private String s1;public int i1;public static float PI = 3.14159f;public Test () {S Ystem.out.println ("I am a constructive method without reference");} Public Test (String s1) {super (); this.s1 = S1; System.out.println ("I am a constructor with a parameter");} Public Test (String s1,int i1) {System.out.println ("I am a constructor with two parameters");} public void sum (int a,int b) {System.out.println ("a+b =" + (a+b));}}




① gets information about a class:

public static void Gettheclass () {Class Class1 = Test.class; System.out.println (Class1.getname ()); System.out.println (Class1.getsimplename ());}

Run:



② Get constructed method:

Get the construction method by Constructor this API:

Provides four ways to call:

Constructor getconstructor (class[] params) --Get a public constructor that uses a special parameter type,

constructor[] GetConstructors () --Get all public constructors for the class

Constructor getdeclaredconstructor (class[] params) --Get constructors that use specific parameter types (regardless of access level)

constructor[] getdeclaredconstructors () --Get all constructors for the class (regardless of access level)


code example:

public static void GetConstructor () {Class Class1 = Test.class; Constructor[] cs = class1.getdeclaredconstructors (); for (Constructor Constructor:cs) {System.out.print ( Constructor.getname () + "(");//Gets the corresponding data type of the constructor's parameter list: class[] paramtypes = Constructor.getparametertypes (); for (Class Class2:paramtypes) {System.out.print (Class2.getsimplename () + ",");} System.out.println (")");}}

Run:





③ Get member variables:

To get the relevant member variable, you need to use the Field API:

There are also four methods available for invocation:

Field GetField (String name) --Get a named public field

field[] GetFields () --Get all public fields of the class

Field Getdeclaredfield (String name) --Get the named field of the class declaration

field[] Getdeclaredfields () --Get all the fields of the class declaration


code example:

public static void GetField () {Class Class1 = Test.class; field[] field = Class1.getfields (); for (Field field:fields) {//Gets the data type of the member variable class FieldType = Field.gettype (); String TypeName = Fieldtype.getname ();//Gets the parameter name of the member variable string filedname = Field.getname (); System.out.println (typename+ "" +filedname);}


Run:








④ Get the relevant method:

The method API is used to get the related methods in the class:

There are also four methods available for invocation:

Method GetMethod (String name, class[] params) --Use a specific parameter type to get a named public method

method[] GetMethods () --Get all public methods of the class

Method Getdeclaredmethod (String name, class[] params) --Use a close-up parameter type to get a naming method for class declarations

method[] Getdeclaredmethods () --Get all the methods of class declaration without permission



code example:

① get all the public methods in the class:

public static void GetMethod () {Class Class1 = Test.class; Method[] methods = Class1.getmethods (); for (int i = 0;i < methods.length;i++) {//Get method return value class ReturnType = methods[i].ge Treturntype (); System.out.print (Returntype.getname () + "");//Get Method name System.out.print (methods[i].getname () + "(");//Get parameter list class[] Paramtypes = Methods[i].getparametertypes (); for (Class class2:paramtypes) {System.out.print (Class2.getname () + ",");} System.out.println (")");}}

Run:


In addition to our custom methods, we have seen some other methods, which are some of the methods provided by the parent class ~


② uses reflection to invoke related methods:

code example:

public static void Usemethod () throws exception{test test = new test (); Class Class1 = Test.getclass (); method = Class1.getmethod ("sum", Int.class,int.class), Object object = Method.invoke (test, New object[]{11,22});

Run:


Of course, do not forget to catch the exception when calling this method!






using Reflection instances in 3.Android:

Some examples of the reflection mechanism in Android, such as: Android after the 1.1 version of the answer and hang off the API to hide

, we can invoke the relevant method in Itelephony by Aidl + reflection mechanism, in view of space, the time relationship here

For an example of the reflection mechanism in Android, refer to the following information :

①android answer and hang-up phone implementation:

Http://blog.sina.com.cn/s/blog_5da93c8f0101g4wb.html

② use the reflection mechanism to close the dialog box by using the button:

http://blog.csdn.net/nokiaguy/article/details/5770263


PS: In addition, seemingly Android 4.1 after the answer to the call method is not possible, the high version of the solution is as follows:

Http://bbs.51cto.com/thread-1078059-1.html



Well, about the Java reflection briefly understand here, follow-up encounter related re-mark~






Analysis of Java reflection mechanism + application examples

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.