我有大约20个Java程序,每个程序都包含一个main()函数。我想给他们所有人打电话,检查异常情况。
是否有方法从另一个java程序调用java程序,并获得返回的异常?
发布于 2014-04-04 12:14:40
public class Main{
public static void main(String args[]){
try{
AnotherClass.main(null); // null inserted for string[] args in the AnotherClass.main
catch(Exception ex){
//do whatever you want
}
}
}调用主类
java Main它将运行AnotherClass main,您可以捕获异常。
发布于 2014-04-04 14:37:03
你可以用反射。只需在一个文件或dataBase中使用所有类名,然后使用以下步骤
List<String> listOfJavaFiles = new ArrayList<String>();
//
listofJavaFiles.add("package.className");
---
//
for(String fileName = listOfJavaFiles){
Class<?> cl = Class.forName(fileName );
Method mh = null;
try {
mh = cl.getMethod("main",String[].class);
} catch (NoSuchMethodException nsme) {
} catch (SecurityException se) {
}
if(mh!=null){
try {
mh.invoke(null,(Object)new String[0]);
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
} catch (InvocationTargetException e) {
}catch(Exception e){
//your logic should go here
////The exception will get thrown here for your main program provided your main program does not throw IllegalAccessException ,IllegalArgumentException and InvocationTargetException
}
}
}发布于 2014-04-04 15:01:19
虽然您当然可以调用父类中的所有静态main(有反射或没有输出反射),但我强烈建议您重构代码并使所有这些类实现一个接口。
public interface CustomMain {
public void doMain(String args[]);
}
public class OneOfTheMainClasses implements CustomMain {
public static void main(String args[]) {
new OneOfTheMainClasses().doMain(args); // for backward compat.
}
public void doMain(String args[]) { //work here }
}然后,在您的代码中,您将创建每个具有main并实现CustomMain的类,并将它们放入List<CustomMain>中。
List<CustomMain> mains = ...; //(Either use reflection or manually add the instances)
for (CustomMain m : mains) {
try {
m.doMain(args);
} catch (Exception e) {
// do what you want here.
}
}你应该重构的一个重要原因..。static main有一个隐式契约,即入口点和出口点。也就是说,static main可以调用System.exit(0)或其他各种退出过程。
https://stackoverflow.com/questions/22862117
复制相似问题