Java反射调用未知的方法

来源:互联网 发布:通讯录防爆软件 编辑:程序博客网 时间:2024/05/16 00:39


背景:在接口测试中档参数从Excel、cvs等外部数据源取数据时,会遇到这样的情况,接口当中某个参数需要传一个动态的值,比如说时间戳,需要获取当前时间。

解决方法:可以单独编写方法,在数据源中此参数的值设置为我们预先写好的方法,程序通过此方法得到想要的数据并传入参数

难点:方法和方法所在的类,对于拥有固定运行逻辑的接口执行程序是未知的。调用已知方法在网上有很多资料,不多阐述。

 

首先,编写需要被调用的类和方法

 

然后编写调用方法,将需要被调用的方法路径当做参数传入

 

最后写一个简单的单元测试

 

 

附源码:

package demo.ref;

import java.text.SimpleDateFormat;

import java.util.Date;

public classTargetClass {

  publicString getCurrencyTime(){

     StringcurrencyTime = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss").format(new Date());

     returncurrencyTime;

  }

}



package demo.ref;

import java.lang.reflect.Method;

public classReflectDemoClass {

  publicvoid invokedMethod(String methodPath)throws ClassNotFoundException,ReflectiveOperationException,SecurityException{

     String[]methodInfo = methodPath.split("\\.");

     StringmethodName = methodInfo[methodInfo.length-1];

     StringclassName = methodPath.substring(0,methodPath.length()-methodName.length()-1);

    

     Class<?>targetClass = Class.forName(className);

     MethodtargetMethod = targetClass.getDeclaredMethod(methodName);

     Stringtime = (String)targetMethod.invoke(targetClass.newInstance());

     System.out.println(time);

  }

}

 

 

package demo.ref;

import org.junit.Test;

public classReflectDemoClassTest {

  @Test

  publicvoid test() throws ClassNotFoundException,SecurityException,ReflectiveOperationException {

     ReflectDemoClassdemo = new ReflectDemoClass();

     demo.invokedMethod("demo.ref.MethodDemo.getCurrencyTime");

  }

}

}

0 0