Java动态调用类方法实例

一.概述

       在前面已经介绍了关于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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值