Android基于反射技术实现的加减乘除运算示例

Android基于反射技术实现的加减乘除运算示例,第1张

概述本文实例讲述了Android基于反射技术实现的加减乘除运算。分享给大家供大家参考,具体如下:

本文实例讲述了AndroID基于反射技术实现的加减乘除运算。分享给大家供大家参考,具体如下:

JAVA反射机制定义:

JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。

Java反射机制主要提供了以下功能: 在运行时判断任意一个对象所属的类;在运行时构造任意一个类的对象;在运行时判断任意一个类所具有的成员变量和方法;在运行时调用任意一个对象的方法;生成动态代理。

有时候我们说某个语言具有很强的动态性,有时候我们会区分动态和静态的不同技术与作法。我们朗朗上口动态绑定(dynamic binding)、动态链接(dynamic linking)、动态加载(dynamic loading)等。然而“动态”一词其实没有绝对而普遍适用的严格定义,有时候甚至像对象导向当初被导入编程领域一样,一人一把号,各吹各的调。

一般而言,开发者社群说到动态语言,大致认同的一个定义是:“程序运行时,允许改变程序结构或变量类型,这种语言称为动态语言”。从这个观点看,Perl,Python,Ruby是动态语言,C++,Java,C#不是动态语言。

尽管在这样的定义与分类下Java不是动态语言,它却有着一个非常突出的动态相关机制:Reflection。这个字的意思是 “反射、映象、倒影”,用在Java身上指的是我们可以于运行时加载、探知、使用编译期间完全未知的classes。换句话说,Java程序可以加载一个 运行时才得知名称的class,获悉其完整构造(但不包括methods定义),并生成其对象实体、或对其fIElds设值、或唤起其methods1。 这种“看透class”的能力(the ability of the program to examine itself)被称为introspection(内省、内观、反省)。Reflection和introspection是常被并提的两个术语。

以上摘录自百度百科,在AndroID 中有很多类是被封闭的,比如 ServiceManager 蓝牙模块更是有N多个类被AndroID 隐藏不开放,要调用这些类必须使用java 的反射技术将类转为对象进行 *** 作.AndroID 应用也是基于JAVA 语言为基础,当然也具备反射这一技术,下面我写了一个DEMO 是如何通过反射技术调用类名方法并完成一个加减乘除的记算器。

首先我们定义一个类,此为只是简单的定义几个方法,即加减乘除四个方法,代码如下:

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;  }}

界面布局文件代码

<?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"      androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content"></button>    <button androID:text="-" androID:ID="@+ID/button02"      androID:layout_wIDth="wrap_content" androID: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:layout_height="wrap_content"></button>  </linearLayout></linearLayout>

下面就是一些对反射技术的 *** 作代码了,由于本篇是反射机制的入门篇,在此只是通过一个小DEMO 讲解反射的常用的几个方法,这里的流程如下:

获取相应的类对象名称

Class<?> classtype = Class.forname("com.terry.operationClass");

如果知道类名并且类名存在于我们工程中,即jar 文件中包含可以使用如下写法

Class<?> classtype = operationClass.class;

返回本类对象

Object invokeOperation = classtype.newInstance();

根据类对象名称去查找对应的方法

Method addMethod = classtype.getmethod("add",new Class[] {          int.class,int.class });

参数一:代码需要查找类名的方法,参数二:指定查找方法的参数类型

调用查找 到的方法执行此方法的处理

Object result = addMethod.invoke(invokeOperation,new Object[] {  new Integer(first),new Integer(second)});

通过调用查找到的方法即可实现方法体的功能。

Tip:反射比较耗费系统资源,建议不在不得以的情况下不要用,尤其是在移动设备上这种对资源要求十分苛刻的设备。

运行效果如下:

下面给出全部页面代码:

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 first,second;  String operaionFun = "";  /** Called when the activity is first created. */  @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-generated method stub      first = 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,first,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 first   * @param second   * @return   * @throws ClassNotFoundException   * @throws illegalaccessexception   * @throws InstantiationException   * @throws SecurityException   * @throws NoSuchMethodException   * @throws IllegalArgumentException   * @throws InvocationTargetException   */  String operation(String oper,int first,int second)      throws ClassNotFoundException,illegalaccessexception,InstantiationException,SecurityException,NoSuchMethodException,IllegalArgumentException,InvocationTargetException {    // 获取相应的类对象名称    Class<?> classtype = Class.forname("com.terry.operationClass");    // 如果知道类名并且类名存在于我们工程中,即jar 文件中包含可以使用如下写法    //Class<?> classtype = operationClass.class;    // 返回本类对象    Object invokeOperation = classtype.newInstance();    if (oper.equals("+")) {      // 根据类对象名称去查找对应的方法      Method addMethod = classtype.getmethod("add",int.class });      // 调用查找 到的方法执行此方法的处理      Object result = addMethod.invoke(invokeOperation,new Object[] {          new Integer(first),new Integer(second) });      return result.toString();    } else if (oper.equals("-")) {      Method cutMethod = classtype.getmethod("cut",int.class });      Object result = cutMethod.invoke(invokeOperation,new Integer(second) });      return result.toString();    } else if (oper.equals("*")) {      Method rIDeMethod = classtype.getmethod("rIDe",int.class });      Object result = rIDeMethod.invoke(invokeOperation,new Integer(second) });      return result.toString();    } else if (oper.equals("/")) {      Method execMthod = classtype.getmethod("Except",int.class });      Object result = execMthod.invoke(invokeOperation,new Integer(second) });      return result.toString();    }    return "";  }}

Tip:在JAVA中可以通过main 函数打印,在AndroID 好像调用会出错

更多关于AndroID相关内容感兴趣的读者可查看本站专题:《Android调试技巧与常见问题解决方法汇总》、《Android开发入门与进阶教程》、《Android多媒体 *** 作技巧汇总(音频,视频,录音等)》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》

希望本文所述对大家AndroID程序设计有所帮助。

总结

以上是内存溢出为你收集整理的Android基于反射技术实现的加减乘除运算示例全部内容,希望文章能够帮你解决Android基于反射技术实现的加减乘除运算示例所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1147878.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存