我是java的初学者。当一个试图用参数"Media 1"(在NetBens中)运行这个程序时,我会收到以下消息。文件名为Media.java。有人能帮我吗?
线程"main"java.lang.RuntimeException异常:不可执行的源代码-未报告的异常java.lang.ClassNotFoundException;必须被抓住或宣布被扔在Media.main(Media.java:23)Java结果:1
import java.lang.reflect.Method;
public class Media {
public boolean test1(String s) {
System.out.println(s);
return true;
}
public int test2(String s) {
return 0;
}
public boolean test3(String s) {
return true;
}
public static void main(String... args) {
Class<?> c = Class.forName(args[0]);
Object t = c.newInstance();
Method[] allMethods = c.getDeclaredMethods();
for (Method m : allMethods) {
String mname = m.getName();
if (!mname.equals("main")) {
System.out.println("involking" + mname);
Object o = m.invoke(t, args[1]);
System.out.println("return value " + o.toString());
}
}
}
}
用下面这样的try-catch包围您的代码,因为您调用的方法抛出异常,所以您必须声明或处理它
try {
Class<?> c = Class.forName(args[0]);
Object t = c.newInstance();
Method[] allMethods = c.getDeclaredMethods();
for (Method m : allMethods) {
String mname = m.getName();
if (!mname.equals("main")) {
System.out.println("involking" + mname);
Object o = m.invoke(t, args[1]);
System.out.println("return value " + o.toString());
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
。。。
public static void main(String…args)throws ClassNotFoundException、InstantiationException、IllegalAccessException、IlllegalArgumentException、InvocationTargetException{
或者使用try/catch块