"Android Development Experience" uses reflection to get a class of fields, methods, and implements a simple call

Source: Internet
Author: User

This article is ready to launch the Android ICO framework, so assume you want a recent study on Android's ICO student framework. You can look at it a little bit.

First, introduce the reflection in Java.

The Java reflection mechanism is in the execution state, and for any arbitrary class, you can know all the properties and methods of the class. For any arbitrary object, you can invoke its arbitrary method and properties. Such dynamic access to information and the ability to dynamically invoke the object's methods is called the reflection mechanism of the Java language .

I don't know if you can understand this kind of explanation. Let's say it's more simple. Reflection is the ability to instantiate a real object based on the class name you give. Therefore, instantiation of an object is not a dead letter. We are able to instantiate different objects, depending on the class name passed in. This approach can be very well combined with the factory design pattern, allowing for more flexible creation of objects.

Following. Let's briefly describe how to use reflection to create objects, and how to get and use methods and fields.

First, give the code for the entity class that you want to use, focusing on the modifiers for the fields and methods ' permissions

Package edu.qust.demo;/** *  * @ClassName: Person * @Description: the person entity class * @author: Zhaokaiqiang * @time: On 2014-7-18 Afternoon 10:41:23 * @version: V1.0 */public class Person {private int age;private string name;protected int height;public string s Chool; Person () {this.name = ' person '; age = 22;} Person (String name) {this.name = name;} private string ShowName (string _name) {return "My name is" + _name;} public void Setage (int.) {this.age = age;} public int getage () {return age;} @Overridepublic String toString () {return "My name is" + name + ", I ' m" + Age + "Years";}}

Below, we start to introduce. In Java, how to use code to implement reflection.

Here are the test procedures

Package Edu.qust.demo;import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;public class Main {private static person person;private static class<person> cls;@ Suppresswarnings ("unchecked") public static void main (string[] args) {person = new person ("Zhao"); cls = (class<person& gt;) Person.getclass (); Creatclassbyreflection ();p rintallmethods ();p rintallfileds (); Invokeprivatemothod (); /** * Use reflection to create an object */private static void Creatclassbyreflection () {try {person accpteacher = (person) class.forname ("Edu.qust. Demo. Person "). Newinstance (); System.out.println (Accpteacher.tostring ()); System.out.println ();} catch (Instantiationexception e) {e.printstacktrace ();} catch (Illegalaccessexception e) {e.printstacktrace ();} catch ( ClassNotFoundException e) {e.printstacktrace ();}} /** * Gets and calls the private method */private static void Invokeprivatemothod () {try {//Get method named ShowName, the number of parameters is String type method = Cls.getd Eclaredmethod ("ShowName", string.class);//IfCall the private method. Java must be suppressed to check for permissions method.setaccessible (TRUE);//Use Invoke to invoke methods. And gets the return value of the method. The object that needs to pass in the class of a method, new object[]//{"Kai"} is the argument that needs to be passed in, corresponding to the string.class above, string string = (String) method.invoke (person,new Object[] {"Kai"}); System.out.println (string);} catch (Nosuchmethodexception e) {e.printstacktrace ();} catch (SecurityException e) {e.printstacktrace ();} catch ( Illegalaccessexception e) {e.printstacktrace (),} catch (IllegalArgumentException e) {e.printstacktrace ();} catch ( InvocationTargetException e) {e.printstacktrace ();}} /** * Gets and prints all field names */private static void Printallfileds () {field[] field = Cls.getdeclaredfields (); System.out.println ("GetFields (): Get full permission modifier decorated field"); for (field F:field) {System.out.println ("field Name =" + F.getname () );} System.out.println ();} /** * Gets and prints all method names */private static void Printallmethods () {method[] method = Cls.getdeclaredmethods (); System.out.println ("Getdeclaredmethods (): Gets the full permission modifier decorated Method"); for (method M:method) {System.out.println ("method Name = "+ M.getname ());} System.out.println ();}}

The following is the output of the test procedure above

My name is person, I ' M Years Oldgetdeclaredmethods (): Gets the full permission modifier decorated by methodmethod name = Tostringmethod name = Shownamemet Hod name = Setagemethod name = Getagegetfields (): Gets the full permission modifier decorated fields field name = Agefield Name = NameField name = Heightfield N Ame = Schoolmy name is Kai

In the Java.lang.reflect package, classes and interfaces are provided to obtain reflection information about classes and objects.


Here, we are now focusing only on the two classes of field and method, representing the member variables and methods of the class, respectively.

Besides. In Java.lang.Class. There is also a very important class that the reflection needs to use, class, which encapsulates a class of all the information, including the various county modifier modified member variables and methods. Therefore, we can use this class to get all kinds of information about the class. class inherits from object, and it takes advantage of Object.getclass to get the class object of an object at execution time.

The main thing we do is get a class object. This object can then be used to get all the member variables and methods of a class, and to invoke the method of arbitrary permission modifier decoration. is casual, even the method of the private decorated class. We can also use reflection to make calls, so it can be said that reflection is quite counter-heavenly.

First look at the output of the first method

My name is person, I ' M years

Here, we instantiate an object with the name of a string string of a class. That's what the above says. Different objects can be created, depending on the string passed in.

Calling the Newinstance method, Java will look for the default constructor, complete the initialization of the object, and thus get this result.

And look at the output of the second method.

Getdeclaredmethods (): Gets the full permission modifier decorated method
Method Name = toString
Method Name = ShowName
Method Name = Setage
Method Name = Getage

We use Getdeclaredmethods to get all the methods inside the class, and then we iterate and simply output the class name.

The result of the third method is almost the same as the second one, just to change the method to filed and then output the field name.

GetFields (): Gets the full permission modifier decorated field
Field Name = Age
Field name = Name
Field Name = height
Field Name = School

In the fourth method, we obtain a detailed method based on the method name, and then pass in the argument. Invokes the method with Invoke.

You must set Method.setaccessible (true) before calling again, and you can call methods that use the private adornment.

In addition to the above code, the class class has a lot of other methods. A lot of other detailed use, or read the document to go.




Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

"Android Development Experience" uses reflection to get a class of fields, methods, and implements a simple call

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.