Java動態調用類方法執行個體

來源:互聯網
上載者:User
一.概述

       在前面已經介紹了關於Java.lang.reflect.*包中的一些基本的知識。這裡通過對上文提供的一個執行個體進行實際編程並測試。

       這裡分別使用了兩個包中的兩個類。所用到的包及包中的檔案清單如下:

testclass包:該包中包含一個編譯過的類class1,該類只有一個方法add。

dyn_callmethod包:該包中包含一個已編譯的類callclass,該類包含做為主調函數的主函數main()。該函數將實現動態調用testclass包中的class1類的add函數。

二.原始碼

1.testclass包的class1類:

package testclass;

public class class1 {

  public class1() {

  }

  public int add(int a,int b){

    return a+b;

  }

}

2.dyn_callmethod包中的callclass類:

package dyn_callmethod;

import java.lang.reflect.*;

import testclass.*;

public class callclass {

  public callclass() {

  }

  public static void main(String args[]){

    try{

      Class cls = Class.forName("testclass.class1");

      System.out.println("Load the target class");

      Class partypes[] = new Class[2];

      partypes[0] = Integer.TYPE;

      partypes[1] = Integer.TYPE;

      Method meth = cls.getMethod("add", partypes);

      System.out.println("get the method of the class");

      testclass.class1 methobj = new testclass.class1();

      Object arglist[] = new Object[2];

      arglist[0] = new Integer(37);

      arglist[1] = new Integer(47);

      Object retobj = meth.invoke(methobj, arglist);

      Integer retval = (Integer)retobj;

      System.out.println(retval.intValue());

    }

    catch(Exception e){

      System.err.println(e);

    }

  }

}

3.運行後輸出結果:

Load the target class

get the method of the class

84

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.