안 드 로 이 드 가 반사 기술 을 바탕 으로 실현 한 가감 승제 연산 예시

11975 단어 Android반사
본 고의 실례 는 안 드 로 이 드 가 반사 기술 을 바탕 으로 실현 한 가감 승제 연산 을 서술 하 였 다.여러분 께 참고 하도록 공유 하 겠 습 니 다.구체 적 으로 는 다음 과 같 습 니 다.
JAVA 반사 메커니즘 정의:
JAVA 반사 메커니즘 은 운행 상태 에서 임의의 종류 에 대해 이 종류의 모든 속성 과 방법 을 알 수 있다.임의의 대상 에 대해 서 는 그것 의 임의의 방법 을 호출 할 수 있다.이러한 동적 으로 얻 은 정보 와 동적 호출 대상 의 방법 을 자바 언어의 반사 메커니즘 이 라 고 한다.
자바 반사 체 제 는 주로 다음 과 같은 기능 을 제공 합 니 다.실행 할 때 임의의 대상 이 속 한 종 류 를 판단 합 니 다.운행 할 때 임의의 종류의 대상 을 구성한다.실행 할 때 임의의 클래스 가 가지 고 있 는 구성원 변수 와 방법 을 판단 합 니 다.실행 할 때 임의의 대상 을 호출 하 는 방법;동적 에이전트 생 성.
때때로 우 리 는 어떤 언어 가 매우 강 한 동태 성 을 가지 고 있다 고 말 하 는데,때때로 우 리 는 동태 와 정태 의 서로 다른 기술 과 방법 을 구분한다.동적 연결(dynamic binding),동적 링크(dynamic linking),동적 로드(dynamic loading)등 이 있 습 니 다.그러나'동태'라 는 단 어 는 절대적 이 고 보편적으로 적용 되 는 엄격 한 정의 가 없다.가끔 은 대상 가이드 가 처음에 프로 그래 밍 분야 에 도 입 된 것 처럼 한 사람 이 번 호 를 하나씩 부 르 고 각자 의 곡 조 를 불 기도 한다.
일반적으로 개발 자 커 뮤 니 티 는 동적 언어 에 대해 대체적으로 인정 하 는 정 의 는'프로그램 이 실 행 될 때 프로그램 구조 나 변수 유형 을 바 꿀 수 있 고 이런 언어 를 동적 언어 라 고 부른다'는 것 이다.이 관점 에서 볼 때 Perl,Python,Ruby 는 동적 언어 입 니 다.C+,자바,C\#는 동적 언어 가 아 닙 니 다.
이러한 정의 와 분류 에서 자바 는 동적 언어 가 아니 지만 매우 뚜렷 한 동적 관련 체 제 를 가진다.Reflection.이 글 자 는'반사,이미지,그림자'라 는 뜻 으로 자바 에 사용 되 는 것 은 우리 가 실행 할 때 불 러 오고 탐색 하 며 컴 파일 하 는 동안 전혀 알 수 없 는 classes 를 말 합 니 다.다시 말 하면 자바 프로그램 은 실행 할 때 이름 을 알 수 있 는 class 를 불 러 올 수 있 으 며,전체 구 조 를 알 수 있 으 며,대상 의 실 체 를 생 성하 거나,fields 에 값 을 설정 하거나,methods 1 을 불 러 올 수 있 습 니 다.이러한'클래스 를 꿰 뚫 어 보 는'능력(the ability of the program to examine itself)을 인 트 로 스 펙 션(내성,내관,반성)이 라 고 한다.Reflection 과 introspection 은 자주 제기 되 는 두 가지 용어 다.
이상 은 바 이 두 백과 에서 발췌 한 것 으로 안 드 로 이 드 에서 여러 가지 유형 이 폐쇄 되 었 습 니 다.예 를 들 어 ServiceManager 블 루 투 스 모듈 은 N 여러 가지 유형 이 안 드 로 이 드 에 의 해 숨겨 져 개방 되 지 않 습 니 다.이런 유형 을 호출 하려 면 자바 의 반사 기술 을 사용 하여 종 류 를 대상 으로 조작 해 야 합 니 다.안 드 로 이 드 응용 도 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 });

매개 변수 1:코드 는 클래스 이름 을 찾 는 방법 이 필요 합 니 다.매개 변수 2:검색 방법의 매개 변수 유형 을 지정 합 니 다.
찾 은 방법 을 호출 하여 이 방법 을 실행 합 니 다.

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", new Class[] {
          int.class, 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", 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 함 수 를 통 해 인쇄 할 수 있 습 니 다.Android 에서 호출 이 잘못된 것 같 습 니 다.
더 많은 안 드 로 이 드 관련 내용 에 관심 이 있 는 독자 들 은 본 사이트 의 주 제 를 볼 수 있다.,,,,,,,
본 고 에서 말 한 것 이 여러분 의 안 드 로 이 드 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기