Android基于反射技術(shù)實現(xiàn)的加減乘除運算示例
本文實例講述了Android基于反射技術(shù)實現(xiàn)的加減乘除運算。分享給大家供大家參考,具體如下:
JAVA反射機(jī)制定義:
JAVA反射機(jī)制是在運行狀態(tài)中,對于任意一個類,都能夠知道這個類的所有屬性和方法;對于任意一個對象,都能夠調(diào)用它的任意一個方法;這種動態(tài)獲取的信息以及動態(tài)調(diào)用對象的方法的功能稱為java語言的反射機(jī)制。
Java反射機(jī)制主要提供了以下功能: 在運行時判斷任意一個對象所屬的類;在運行時構(gòu)造任意一個類的對象;在運行時判斷任意一個類所具有的成員變量和方法;在運行時調(diào)用任意一個對象的方法;生成動態(tài)代理。
有時候我們說某個語言具有很強(qiáng)的動態(tài)性,有時候我們會區(qū)分動態(tài)和靜態(tài)的不同技術(shù)與作法。我們朗朗上口動態(tài)綁定(dynamic binding)、動態(tài)鏈接(dynamic linking)、動態(tài)加載(dynamic loading)等。然而“動態(tài)”一詞其實沒有絕對而普遍適用的嚴(yán)格定義,有時候甚至像對象導(dǎo)向當(dāng)初被導(dǎo)入編程領(lǐng)域一樣,一人一把號,各吹各的調(diào)。
一般而言,開發(fā)者社群說到動態(tài)語言,大致認(rèn)同的一個定義是:“程序運行時,允許改變程序結(jié)構(gòu)或變量類型,這種語言稱為動態(tài)語言”。從這個觀點看,Perl,Python,Ruby是動態(tài)語言,C++,Java,C#不是動態(tài)語言。
盡管在這樣的定義與分類下Java不是動態(tài)語言,它卻有著一個非常突出的動態(tài)相關(guān)機(jī)制:Reflection。這個字的意思是 “反射、映象、倒影”,用在Java身上指的是我們可以于運行時加載、探知、使用編譯期間完全未知的classes。換句話說,Java程序可以加載一個 運行時才得知名稱的class,獲悉其完整構(gòu)造(但不包括methods定義),并生成其對象實體、或?qū)ζ鋐ields設(shè)值、或喚起其methods1。 這種“看透class”的能力(the ability of the program to examine itself)被稱為introspection(內(nèi)省、內(nèi)觀、反?。?。Reflection和introspection是常被并提的兩個術(shù)語。
以上摘錄自百度百科,在Android 中有很多類是被封閉的,比如 ServiceManager 藍(lán)牙模塊更是有N多個類被Android 隱藏不開放,要調(diào)用這些類必須使用java 的反射技術(shù)將類轉(zhuǎn)為對象進(jìn)行操作.Android 應(yīng)用也是基于JAVA 語言為基礎(chǔ),當(dāng)然也具備反射這一技術(shù),下面我寫了一個DEMO 是如何通過反射技術(shù)調(diào)用類名方法并完成一個加減乘除的記算器。
首先我們定義一個類,此為只是簡單的定義幾個方法,即加減乘除四個方法,代碼如下:
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>
下面就是一些對反射技術(shù)的操作代碼了,由于本篇是反射機(jī)制的入門篇,在此只是通過一個小DEMO 講解反射的常用的幾個方法,這里的流程如下:
獲取相應(yīng)的類對象名稱
Class<?> classType = Class.forName("com.terry.operationClass");
如果知道類名并且類名存在于我們工程中,即jar 文件中包含可以使用如下寫法
Class<?> classType = operationClass.class;
返回本類對象
Object invokeOperation = classType.newInstance();
根據(jù)類對象名稱去查找對應(yīng)的方法
Method addMethod = classType.getMethod("add", new Class[] { int.class, int.class });
參數(shù)一:代碼需要查找類名的方法,參數(shù)二:指定查找方法的參數(shù)類型
調(diào)用查找 到的方法執(zhí)行此方法的處理
Object result = addMethod.invoke(invokeOperation, new Object[] { new Integer(first), new Integer(second) });
通過調(diào)用查找到的方法即可實現(xiàn)方法體的功能。
Tip:反射比較耗費系統(tǒng)資源,建議不在不得以的情況下不要用,尤其是在移動設(shè)備上這種對資源要求十分苛刻的設(shè)備。
運行效果如下:
下面給出全部頁面代碼:
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 { // 獲取相應(yīng)的類對象名稱 Class<?> classType = Class.forName("com.terry.operationClass"); // 如果知道類名并且類名存在于我們工程中,即jar 文件中包含可以使用如下寫法 //Class<?> classType = operationClass.class; // 返回本類對象 Object invokeOperation = classType.newInstance(); if (oper.equals("+")) { // 根據(jù)類對象名稱去查找對應(yīng)的方法 Method addMethod = classType.getMethod("add", new Class[] { int.class, int.class }); // 調(diào)用查找 到的方法執(zhí)行此方法的處理 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", new Class[] { int.class, int.class }); Object result = cutMethod.invoke(invokeOperation, new Object[] { new Integer(first), new Integer(second) }); return result.toString(); } else if (oper.equals("*")) { Method rideMethod = classType.getMethod("ride", new Class[] { int.class, int.class }); Object result = rideMethod.invoke(invokeOperation, new Object[] { new Integer(first), new Integer(second) }); return result.toString(); } else if (oper.equals("/")) { Method execMthod = classType.getMethod("Except", new Class[] { int.class, int.class }); Object result = execMthod.invoke(invokeOperation, new Object[] { new Integer(first), new Integer(second) }); return result.toString(); } return ""; } }
Tip:在JAVA中可以通過main 函數(shù)打印,在Android 好像調(diào)用會出錯
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android調(diào)試技巧與常見問題解決方法匯總》、《Android開發(fā)入門與進(jìn)階教程》、《Android多媒體操作技巧匯總(音頻,視頻,錄音等)》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)》
希望本文所述對大家Android程序設(shè)計有所幫助。
相關(guān)文章
Android ListView自動顯示隱藏布局的實現(xiàn)方法
這篇文章主要介紹了Android ListView自動顯示隱藏布局的實現(xiàn)方法的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-09-09詳解Android應(yīng)用開發(fā)中Intent的作用及使用方法
這篇文章主要介紹了Android應(yīng)用開發(fā)中Intent的作用與用法,包括如何激活A(yù)ctivity組件與Intent的投遞等,需要的朋友可以參考下2016-03-03Android獲取手機(jī)系統(tǒng)版本等信息的方法
這篇文章主要介紹了Android獲取手機(jī)系統(tǒng)版本等信息的方法,涉及Android獲取手機(jī)版本中各種常見信息的技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04Android實戰(zhàn)打飛機(jī)游戲之實現(xiàn)主角以及主角相關(guān)元素(3)
這篇文章主要為大家詳細(xì)介紹了Android實戰(zhàn)打飛機(jī)游戲之實現(xiàn)主角以及主角相關(guān)元素,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-07-07Android 懸浮窗權(quán)限各機(jī)型各系統(tǒng)適配大全(總結(jié))
這篇文章主要介紹了Android 懸浮窗權(quán)限各機(jī)型各系統(tǒng)適配大全(總結(jié)),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08android: targetSdkVersion升級中Only fullscreen activities can r
這篇文章主要給大家介紹了關(guān)于Android target SDK和build tool版本升級中遇到Only fullscreen activities can request orientation問題的解決方法,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2018-09-09