这是我的一段代码:(我要做的是:在我的主类中定义一个方法“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
答案 0 :(得分:5)
通过Method
方法获取Class.getMethod
对象。像这样:
RenameScript2.class.getMethod("rename", parameters);
但是,我建议您考虑为可以执行重命名的类编写接口,而不是传递Method
。
这样的界面看起来像
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();
}
答案 1 :(得分:0)
首先,aioobe肯定是正确的,传递一个Method对象有点难看。我假设你已经坚持下去了!
要获得某种方法,您需要使用reflection。以下代码在类toString
上获取了名为Integer
的方法。然后它调用toString
方法。
Method method = Integer.class.getMethod("toString");
Object o = method.invoke(new Integer(7));
System.out.println(o);
静态方法不需要将第一个参数传递给method.invoke
Method method = File.class.getMethod("listRoots");
System.out.println(method.invoke(null));
这说明了你不应该使用它的原因。那个字符串" toString"和" listRoots"不可重构。如果某人重命名了一个方法,那么您将获得一个运行时异常(而不是编译时错误)(因此您需要捕获的例外情况,NoSuchMethodException
和IllegalAccessException
) 。使用反射比使用普通代码慢得多。
答案 2 :(得分:0)
您应该如何做:
RenameScript2
public static String RenamingRule(String input, int file_row)
成为抽象
RenameScriptMain2
延伸到课程RenameScript2
之上,并提供方法RenamingRule()
的实施。main
方法内创建类RenameScriptMain2
的实例并调用方法RenamingRule()