这是我的一段代码:(我要做的是:在我的主类中定义一个方法"renamingrule",实例化我的另一个类"renamescript"的实例并调用它的重命名方法作为参数传递我在主类中定义的"renamingrule"方法.在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
Run Code Online (Sandbox Code Playgroud)
你Method通过Class.getMethod方法掌握了对象.像这样的东西:
RenameScript2.class.getMethod("rename", parameters);
Run Code Online (Sandbox Code Playgroud)
但是,我建议你考虑为一个可以执行重命名的类编写一个接口,而不是传递一个Method.
这样的界面可能看起来像
interface RenameAction {
void performRename();
}
Run Code Online (Sandbox Code Playgroud)
要将脚本包装在RenameAction对象中,您可以执行类似的操作
RenameAction action = new RenameAction() {
void performRename() {
// ...
String command = "cmd /c rename "+_path+"\\"+"\""+next_file+"\" "...
p = Runtime.getRuntime().exec(command);
// ...
}
};
Run Code Online (Sandbox Code Playgroud)
然后你会这样做:
public void rename(RenameAction action) {
action.performRename();
}
Run Code Online (Sandbox Code Playgroud)