Java动态调用类方法实例

来源:互联网 发布:qq三国js用什么奥义 编辑:程序博客网 时间:2024/06/03 16:01
一.概述

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

原创粉丝点击