The application of reflection in Java programming in the development of Android _android

Source: Internet
Author: User
Tags function prototype object object reflection

Reflection definition

Reflection (Reflection) enables programs that run in the JVM to detect and modify run-time behavior.
Why do I need reflection

The benefits of reflection include:

    • Detects the type of an object at run time.
    • Dynamically constructs an object of a class.
    • Detects the properties and methods of a class.
    • Any method that invokes the object.
    • Modifies the visibility of constructors, methods, and properties.

Reflection method
Getdeclaredmethod method

The statement reads as follows:

Public method Getdeclaredmethod (String name, Class<?> ... parametertypes) throws Nosuchmethodexception, SecurityException

Explain:

Returns a method object that reflects the specified declared methods of the class or interface represented by this class object.
1. Name: is a string that specifies the abbreviation for the desired method.
2. Parametertypes: is a variable-length array of class objects that identify the type of the method's parameters in a declared order.

Attention:
Getdeclaredmethod gets the public method or protected method of the class declaration, but does not include inherited methods.
GetMethod Method

The statement reads as follows:

Public method GetMethod (String name, Class<?> ... parametertypes) throws Nosuchmethodexception, SecurityException

Explain:

Returns a method object that reflects the specified public member methods of the class or interface represented by this class object.
1. Name: is a string that specifies the abbreviation for the desired method.
2. Parametertypes: is a variable-length array of class objects that identify the type of the method's parameters in a declared order.

Parameter explanation

The name parameter does not need to be explained, that is, the method name of the calling class.

Perhaps a lot of students just contact this method, will have a question to the parametertypes parameters, such as why this parameter is class generic variable-length array, in fact, for example is very good to understand.

Suppose the method we are going to reflect has 4 parameters, and the function prototype is as follows:

public void Printinfo (String str, int inum, double dnum, long i);

So, by returning to get the method object, the Parametertypes is shown as follows:

GetMethod ("Printinfo", String.class, Int.class, Double.class, Long.class);


So, parametertypes is actually the type abstraction of the method parameters.
Invoke Method

The statement reads as follows:

public object invoke (Object obj, Object ... args) throws Illegalaccessexception, IllegalArgumentException, InvocationTargetException

Explain:

The method class's Invoke (Object obj, Object ... args) methods receive parameters that must be objects. which
1. obj: An object from which the underlying method is invoked.
2. Args: Parameters used for method calls.

Android Reflection Applications

We know that some Android classes are not open in the SDK, for example, you need to get system properties, you need to call to the Systemproperties class's Get method, but this class is not exposed in the SDK, we can view this class in the Android source code:

Package Android.os;

Import java.util.ArrayList;

Import Android.util.Log;


/**
 * gives access to the System Properties store. The System Properties
 * Store contains a list of string key-value pairs.
 *
 * {@hide}
/public class systemproperties
{
  //omitting the specific implementation code
  /**
 * Get the value for the Given key.
 * @return An empty string if the key isn ' t found
 * @throws illegalargumentexception if the key exceeds c16/>*/public
 static string get (String key) {
  if (key.length () > Prop_name_max) {
   throw new Illegalarg Umentexception ("Key.length >" + Prop_name_max);
  }
  return Native_get (key);
 }
}


As you can see, there is a @hide tag in front of this, so this class cannot be invoked directly in the code.

However, in Android apps, many times we need to get to the phone type attribute (Ro.product.model). So, at this point, we need to reflect the Systemproperties class at the application layer and call the Get method. Specific implementation of the source code is as follows:

Import java.lang.reflect.InvocationTargetException;

Import Java.lang.reflect.Method;

Import Android.util.Log;
  public class Systemproperties {public static string get (String key) {String value = ' ";

  Class<?> CLS = null;
   try {cls = Class.forName ("android.os.SystemProperties");
   Method Hidemethod = Cls.getmethod ("Get", string.class);
   Object object = Cls.newinstance ();
  Value = (String) Hidemethod.invoke (object, key);
  catch (ClassNotFoundException e) {log.e ("Zhengyi.wzy", "Get Error ()", e);
  catch (Nosuchmethodexception e) {log.e ("Zhengyi.wzy", "Get Error ()", e);
  catch (Instantiationexception e) {log.e ("Zhengyi.wzy", "Get Error ()", e);
  catch (Illegalaccessexception e) {log.e ("Zhengyi.wzy", "Get Error ()", e);
  catch (IllegalArgumentException e) {log.e ("Zhengyi.wzy", "Get Error ()", e);
  catch (InvocationTargetException e) {log.e ("Zhengyi.wzy", "Get Error ()", e);
 return value; }

}

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.