如何解析一个由静态方法组成的String,以便我们可以调用它?

时间:2016-05-11 12:09:48

标签: java parsing reflection

我试图编写一个接收字符串的函数,该字符串由一个以字符串数组作为参数的静态方法组成。

例如,让我们假设我们这个类有一个静态方法:

package com.stack.examples;

public class Example {

   public static void testMethod() {
       System.out.println("method executed");
    }
}

现在,我们的函数将在另一个类中,如下所示:

package com.stack.functions;

public class Functions {

   public void parseCommand(String command) {
      //TODO, this is where my doubts lie
      //The given string is always composed of a sequence of Java identifiers 
        //separated by the character ’.’, representing the full qualified name of 
          //a Java method (package.class.method)
       command.execute(); //Would this work? Perhaps reflection would be ideal

   }
}

我的目标是解析parseCommand中作为参数给出的字符串,以便

parseCommand("com.stack.examples.Example.testMethod()");

实际上使用给定的参数调用静态方法(在此示例中,该方法仅打印出"消息已执行")。

2 个答案:

答案 0 :(得分:1)

在寻找解决此问题的替代方案后,我发现reflection为我解决了问题:

要执行的静态方法:

ResultSet

主类:

  String sql = "SELECT * FROM test";
  ResultSet rs = stmt.executeQuery(sql);

  if(rs.next()){
      do {

        if (rs.getString("sent").equals("0")) {

          try{
             //if there is a row and it is equals to 0.. so update it to 1.. 

             String sql2 = "UPDATE test SET test='1' WHERE test=....";
             Statement updateStatement = <create statement here>;

             int rs3 = updateStatement.executeUpdate();
             updateStatement.close();
          }catch (SQLException sqlex) { 
             sqlex.printStackTrace();
          }
        }
     }while(rs.next());
   }else {
      try{
             //insert if i couldn't get any rows in the table
             String sql2 = "INSERT INTO test......";
             Statement insertStatement = <create statement here>;
             int rs3 = insertStatement.executeUpdate();
             insertStatement.close();
          }catch (SQLException sqlex) {
             sqlex.printStackTrace();
          }
    }

    rs.close();
    stmt.close();
    conn.close(); 

答案 1 :(得分:0)

使用Java反映: 首先在Example类中搜索equaly命名方法,然后调用它。 也许还要检查您的方法参数method.getParameters()

    Method[] methods = Example.class.getMethods();
    for (Method method : methods) {
        if(method.getName().equals(command)){
            try {
                method.invoke(Example.class, null);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }
相关问题