Question

I am a beginner in java. When a try to run this program with the arguments "Media 1" (In NetBens) I have the following message. The name of the file is Media.java. Can anyone help me?

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown at Media.main(Media.java:23) Java Result: 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());
        }
    }

}

}
Was it helpful?

Solution

surround your code with try catch like below as methods you are calling throws exception so you have to declare or handle it

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();
}

OTHER TIPS

...

public static void main(String... args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

...

or use try/catch blocks

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top