An example of subtraction operation based on the reflection technology of Android _android

Source: Internet
Author: User
Tags gettext reflection

This example describes the Android subtraction operation based on reflection technology. Share to everyone for your reference, specific as follows:

Java Reflection mechanism Definition:

The Java reflection mechanism is in the running state, and for any class, all the properties and methods of the class are known, and any one of its methods can be invoked for any object, and this dynamically acquired information and the function of the method that dynamically invokes the object are called the reflection mechanism of the Java language.

The Java reflection mechanism mainly provides the following features: To determine at run time the class to which any object belongs, to construct an object of any class at run time, to determine the member variables and methods of any class at run time, to invoke a method of any object at run time, and to generate a dynamic proxy.

Sometimes we say that a language has a strong dynamic, and sometimes we distinguish between dynamic and static technologies and practices. We're catchy. Dynamic binding (dynamically binding), dynamic linking, dynamic loading, and so on. However, the term "dynamic" does not have the absolute and universally applicable strict definition, sometimes even like object-oriented was originally imported into the programming domain, one person a number, each blow each tune.

Generally speaking, the developer community speaks of dynamic languages, with a broadly agreed definition of: "When a program runs, it allows you to change the program structure or variable type, which is called a dynamic language." From this point of view, Perl,python,ruby is a dynamic language, c++,java,c# is not a dynamic language.

Although Java is not a dynamic language in this definition and classification, it has a very prominent dynamic correlation mechanism: Reflection. The meaning of this word is "reflection, image, reflection," which is used in Java to refer to the classes that we can load, detect, and use during compilation. In other words, a Java program can load a class that knows its name at run time, learns its full structure (but does not include methods definitions), generates its object entity, or sets a value on its fields, or evokes its methods1. This ability to "See Through Class" (the ability of the program to examine itself) is called introspection (introspective, internal, introspective). Reflection and introspection are two terms that are often mentioned.

The above excerpt from Baidu Encyclopedia, there are many classes in Android is closed, such as ServiceManager Bluetooth module is more than n multiple classes are hidden by Android, to invoke these classes must use Java Reflection technology to convert classes to objects to operate. Android apps are also based on the Java language and, of course, reflective technology, and I've written a demo on how to invoke the class name method through reflection technology and complete a subtraction.

First we define a class, which simply defines several methods, that is, subtraction four methods, the code is as follows:

Class Operationclass {public
  float Add (int parm1, int parm2) {return
    parm1 + parm2;
  }
  public float cut (int parm1, int parm2) {return
    parm1-parm2;
  }
  public float Ride (int parm1, int parm2) {return
    Parm1 * PARM2;
  }
  public float Except (int parm1, int parm2) {return
    parm1/parm2;
  }
}

Interface layout file code

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" fill_parent "android:orientation=" vertical "android:layout_height=" fill_parent " > <edittext android:id= "@+id/edittext01" android:layout_width= fill_parent "android:layout_height=" Wrap_ Content "></EditText> <edittext android:id=" @+id/edittext02 "android:layout_width=" Fill_parent "Android : layout_height= "wrap_content" ></EditText> <textview android:id= "@+id/textview01" Android:layout_
  gravity= "center" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" ></TextView> <linearlayout android:id= "@+id/linearlayout01" android:orientation= Horizontal "android:layout_width=" wrap_ Content "android:layout_height=" wrap_content "> <button android:text=" + "android:id=" @+id/button01 "and Roid:layout_width= "Wrap_content" android:layout_height= "Wrap_content" ></button> <button android:text= "-" android:id= "@+id/button02" android:layout_width= "Wrap_content" Androi d:layout_height= "Wrap_content" ></Button> <button android:text= "*" android:id= "@+id/button03" Android : layout_width= "wrap_content" android:layout_height= "wrap_content" ></Button> <button android:text= "/" Android:id= "@+id/button04" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" ></ button> <button android:text= "=" android:id= "@+id/button05" android:layout_width= "Wrap_content" Android:la

 yout_height= "Wrap_content" ></Button> </LinearLayout> </LinearLayout>

Here are some of the operational code for the reflection technology, because this is the introduction to the reflection mechanism, this is only a small demo to explain the common methods of reflection, here the process is as follows:

Get the corresponding class object name

class<?> ClassType = Class.forName ("Com.terry.operationClass");

If you know the class name and the class name exists in our project, the jar file contains the following notation

class<?> ClassType = Operationclass.class;

Returns the object of this class

Object invokeoperation = Classtype.newinstance ();

Find the corresponding method based on the class object name

Method Addmethod = Classtype.getmethod ("Add", new class[] {
          int.class, int.class});

Parameter one: code needs to find the method of class name, parameter two: Specify the parameter type of the lookup method

Call the lookup method to perform the processing of this method

Object result = Addmethod.invoke (invokeoperation, new object[] {
  new Integer (a), new integer (second)
});

The function of the method body can be realized by invoking the found method.

Tip: Reflection is a waste of system resources and is not recommended, especially on mobile devices, which are demanding resources.

The operation effect is as follows:

All the page codes are given below:

Package Com.terry;
Import java.lang.reflect.InvocationTargetException;
Import Java.lang.reflect.Method;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.TextView;
  public class Operationactivity extends activity {Private EditText one, two;
  Private TextView result;
  Private Button Add, cut, Ride, Except, sum;
  int, second;
  String operaionfun = ""; /** called the activity is a.
    * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.main);
    Findview ();
    Add.setonclicklistener (click);
    Cut.setonclicklistener (click);
    Ride.setonclicklistener (click);
    Except.setonclicklistener (click);
  Sum.setonclicklistener (click);
    } void Findview () {one = (EditText) Findviewbyid (r.id.edittext01); two = (EdittEXT) Findviewbyid (r.id.edittext02);
    result = (TextView) Findviewbyid (R.ID.TEXTVIEW01);
    Add = (Button) Findviewbyid (R.ID.BUTTON01);
    Cut = (Button) Findviewbyid (R.ID.BUTTON02);
    Ride = (Button) Findviewbyid (R.ID.BUTTON03);
    Except = (Button) Findviewbyid (r.id.button04);
  sum = (Button) Findviewbyid (R.ID.BUTTON05); Onclicklistener click = New Onclicklistener () {@Override public void OnClick (View v) {//TODO Auto-gen
      erated method Stub-A-Integer.parseint (One.gettext (). toString ());
      Second = Integer.parseint (Two.gettext (). toString ());
        Switch (V.getid ()) {Case r.id.button01:operaionfun = "+";
      Break
        Case r.id.button02:operaionfun = "-";
      Break
        Case R.id.button03:operaionfun = "*";
      Break
        Case r.id.button04:operaionfun = "/";
      Break
 Case R.id.button05:try {result.settext (Operation (Operaionfun, A, second));       catch (SecurityException e) {//TODO auto-generated catch block E.printstacktrace ();
        catch (IllegalArgumentException e) {//TODO auto-generated catch block E.printstacktrace ();
        catch (ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();
        catch (Illegalaccessexception e) {//TODO auto-generated catch block E.printstacktrace ();
        catch (Instantiationexception e) {//TODO auto-generated catch block E.printstacktrace ();
        catch (Nosuchmethodexception e) {//TODO auto-generated catch block E.printstacktrace ();
        catch (InvocationTargetException e) {//TODO auto-generated catch block E.printstacktrace ();
      } break;
  }
    }
  }; /** * @param oper * @param @param second * @return * @throws CLASSNOTFOUndexception * @throws illegalaccessexception * @throws instantiationexception * @throws SecurityException * Throws Nosuchmethodexception * @throws illegalargumentexception * @throws invocationtargetexception/String o Peration (String oper, int-A, int second) throws ClassNotFoundException, Illegalaccessexception, Instantiat  Ionexception, SecurityException, Nosuchmethodexception, IllegalArgumentException, invocationtargetexception {/
    Gets the corresponding class object name class<?> ClassType = Class.forName ("Com.terry.operationClass");
    If you know the class name and the class name exists in our project, the jar file contains the//class<?> ClassType = Operationclass.class that can be used in the following notation;
    Returns this class object invokeoperation = Classtype.newinstance ();
          if (oper.equals ("+")) {//Find the corresponding method based on the class object name Addmethod = Classtype.getmethod ("Add", new class[] {
      Int.class, int.class});
      Call the lookup method to perform the processing of this method Object result = Addmethod.invoke (invokeoperation, new object[] {    New Integer (a), new Integer (second)});
    return result.tostring (); else if (oper.equals ("-")) {Method Cutmethod = Classtype.getmethod (' Cut ', new class[] {int.class, int.
      class});
      Object result = Cutmethod.invoke (invokeoperation, new object[] {new Integer (a), new Integer (second)});
    return result.tostring (); else if (oper.equals ("*")) {Method Ridemethod = Classtype.getmethod (' Ride ', new class[] {int.class, in
      T.class});
      Object result = Ridemethod.invoke (invokeoperation, new object[] {new Integer (a), new Integer (second)});
    return result.tostring (); else if (oper.equals ("/")) {Method Execmthod = Classtype.getmethod ("Except", new class[] {int.class, I
      Nt.class});
      Object result = Execmthod.invoke (invokeoperation, new object[] {new Integer (a), new Integer (second)});
    return result.tostring ();
  Return "";

 }
}

Tip: You can print from the main function in Java, as if the call would be wrong on Android

For more information on Android-related content readers can view the site topics: "Android Debugging techniques and common problems solution summary", "Android Development introduction and Advanced Course", "Android Multimedia operating skills Summary (audio, video, recording, etc.)", " Android Basic Components Usage Summary, Android View tips Summary, Android layout layout tips and Android Control usage summary

I hope this article will help you with the Android program.

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.