Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使类中的方法名成为动态的?_Java_Eclipse - Fatal编程技术网

Java 如何使类中的方法名成为动态的?

Java 如何使类中的方法名成为动态的?,java,eclipse,Java,Eclipse,当我从类中创建一个对象时,我想使类中的方法名成为动态的。我想动态地执行方法名。下面是我的代码 public static void ExecuteTest() throws Exception { for (int i = 1, j = 1; i < 2; i = i+1, j = j+1) { FW_ReadExcelFile N = new FW_ReadExcelFile(); FW_ReadExcelFile

当我从类中创建一个对象时,我想使类中的方法名成为动态的。我想动态地执行方法名。下面是我的代码

public static void ExecuteTest() throws Exception 
{
    for (int i = 1,  j = 1;  i < 2;  i = i+1, j = j+1)  {    
            FW_ReadExcelFile N = new FW_ReadExcelFile();
            FW_ReadExcelFile.setExcelSheetEnvValues(i,i);
             //java.lang.String Flag2 = N.getTCExecuteFlag() ;

             String Flag = "YES";
             String Flag21 = N.getTCExecuteFlag();


            if ( Flag.equals(Flag21)  ){
                String TCName = N.getTCName();
                FW_Report u = new FW_Report();
                u.TCName; // the FW_Report  class has many methods and I want to call the method on my demand .
            } 
public static void ExecuteTest()引发异常
{
对于(inti=1,j=1;i<2;i=i+1,j=j+1){
FW_ReadExcelFile N=新的FW_ReadExcelFile();
FW_ReadExcelFile.setExcelSheetEnvValues(i,i);
//java.lang.String Flag2=N.getCexecuteFlag();
String Flag=“是”;
String Flag21=N.getCexecuteflag();
如果(标志等于(标志21)){
字符串TCName=N.getTCName();
FW_报告u=新FW_报告();
u、 TCName;//FW_Report类有许多方法,我想根据需要调用该方法。
} 
我想动态地执行方法名

使用来实现这一点

示例代码:

        Class<?> name = Class.forName("ClassName");
        Object instance = name.newInstance();
        Method[] methods = name.getMethods();

        for (Method method : methods) {
            if (method.getName().equals(N.getTCName())) {
                // Match found. Invoke the method. call the method on my demand.
                method.invoke(instance, null);
                break;
            }
        }
使用java反射

java.lang.reflect.Method method = u.getClass().getMethod("getReportName", param1.class, param2.class, ..);

method.invoke(obj,/*param1*/,/*param2*/,....);

getReportName是您要调用的方法名称的一个示例。请参考java反射。

为什么需要这样做?您的代码样式表明您对java已经足够陌生,因此您确实不应该尝试反射。我想执行本地excel工作表中有“是”的方法和有“否”的方法它们应该被忽略。一个方法不能在本地工作表中有一个“是”,一个方法是一段处理变量的代码。谢谢你,Xabster它现在工作得很好:)不会FW_Report u=new FW_Report();已经加载FW_Report类了吗?我认为我们不需要做class.forName();FW_Report.class就足够了。@WhoAmI:是的,这是真的。我们也可以加载它。@AnkurShanbhag:当您只需要Clazz.getMethod(…)时,foreach循环中的点是什么。
java.lang.reflect.Method method = u.getClass().getMethod("getReportName", param1.class, param2.class, ..);

method.invoke(obj,/*param1*/,/*param2*/,....);