Call a function in another class by its string name, from a different class

54 Views Asked by At

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?

0

There are 0 best solutions below