0

Problem

I'm trying to call a method in a class by its name (as a string).

The mso object has the method exampleMethodName.

This works - I can successfully call a function by its string name.

String s1 = "test string 1";
String s2 = "test string 2";

CallToClass mso = new CallToClass();
mso.getClass().getDeclaredMethod("exampleMethodName", String.class, String.class).invoke(mso, s1, s2);

But, when I take the same block of code and put it in a in a class, it fails. Exception:

unreported exception java.lang.NoSuchMethodException; must be caught or declared to be thrown

Example code

class CallToClass {

    public void CallToClass() {}

    public double exampleMethodName(String t1, String t2) {
        return 0.1;
    }

}

class CallFromClass {

    private String t1;
    private String t2;

    public void CallFromClass(String t1 , String t2) {
        this.t1 = t2;
        this.t2 = t1;
    }

    public void Compare() {
        CallToClass mso = new CallToClass();
        mso.getClass().getDeclaredMethod("exampleMethodName", String.class, String.class).invoke(mso, s1, s2);
    }
}

Why might this be? How can I fix it?

Ian
  • 3,605
  • 4
  • 31
  • 66
  • My bad - updated – Ian Nov 13 '20 at 17:33
  • Looks like you forgot to try/catch the `NoSuchMethodException`, which, as a checked exception, must be handled or declared – MDK Nov 13 '20 at 17:35
  • Is this necessary even if I know that the string will _always_ map to a function name? – Ian Nov 13 '20 at 17:36
  • 1
    Indeed, java forces you to handle checked exceptions, see [here](https://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html) and [here](https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html) for the rationale – MDK Nov 13 '20 at 17:38
  • Thanks - this was the correct answer – Ian Nov 13 '20 at 17:50
  • 1
    This is a compile time error, you should just put try/catch around the calling code or add ```throws Throwable``` (or any subclass) to the method declaration – Marcos Vasconcelos Nov 13 '20 at 18:01

0 Answers0