这是我的一段代码:(我想用它做的是:在我的主类中定义一个方法“renamingrule”,实例化我的另一个类“renamescript”的实例并调用它的重命名方法传递作为参数我在主类中定义的“重命名规则”方法。RenamScript 类中的一切都很好,没有错误,但我不知道如何从我的主类/方法调用脚本类的重命名方法。谢谢)
public class RenameScript2 {
...
public void rename(Method methodToCall) throws IOException, IllegalAccessException, InvocationTargetException {
try
{
...
String command = "cmd /c rename "+_path+"\\"+"\""+next_file+"\" "
+"\""+methodToCall.invoke(next_file, next_index)+"\"";
p = Runtime.getRuntime().exec(command);
}catch(IOException e1) {} catch(IllegalAccessException IA1) {} catch(InvocationTargetException IT1) {} ;
}//end of rename
} //end of class
//=======================================
public class RenameScriptMain2 {
public static String RenamingRule(String input, int file_row)
{
String output = "renamed file "+(file_row+1)+".mp3";
return output;
}
public static void main(String[] args) throws IOException
{
RenameScript2 renamer = new RenameScript2();
renamer.setPath("c:\\users\\roise\\documents\\netbeansprojects\\temp\\files");
try{
renamer.rename(RenamingRule);
}catch(IOException e2) {};
System.out.println("Done from main()\n\n");
}
} //end of class
最佳答案
您可以通过 Class.getMethod
方法获取 Method
对象。像这样:
RenameScript2.class.getMethod("rename", parameters);
但是,我建议您考虑为一个可以执行重命名的类编写一个接口(interface),而不是传递一个方法
。
这样的界面看起来像
interface RenameAction {
void performRename();
}
要将脚本包装在 RenameAction
对象中,您可以执行如下操作
RenameAction action = new RenameAction() {
void performRename() {
// ...
String command = "cmd /c rename "+_path+"\\"+"\""+next_file+"\" "...
p = Runtime.getRuntime().exec(command);
// ...
}
};
然后您只需这样做:
public void rename(RenameAction action) {
action.performRename();
}
关于java - 如何调用以方法作为参数的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6190368/