lundi 5 décembre 2022

NoSuchMethodException with List parameter

I am calling a private static method using Java reflection, and that method has as one of its parameters a List. After extensive Googling, I cannot seem to find the right way to get that method for reflection purposes, and I'm getting a NoSuchMethodException when I try to find it:

// In the test file
@Test
@SuppressWarnings("JavaReflectionMemberAccess") // for getDeclaredMethod() call
public void getStringCorrectMessage() {
    try {
        Class<MyException> clazz = MyException.class;
        Method getStringMethod = clazz.getDeclaredMethod( // exception happening here
            "getString", MyEnumObject.class, List.class, Boolean.class);
        getStringMethod.setAccessible(true);
        String actual = (String)getStringMethod.invoke(null, MyEnumObject.VALUE, null, true);
        String expected = "result";
        Assertions.assertEquals(actual, expected);
    } catch (Exception e) {
        Assertions.fail(e.toString());
    }
}

// Package-private static getString() in MyException.java
public class MyException extends Exception {
    static String getString(MyEnumObject myObject, List<String> myList, boolean myBool) {
        return "abc";
    }
}


// Enum class in MyEnumObject.java
public enum MyEnumObject {
    VALUE("blah");

    private final String messageText;
    MyEnumObject(String text) { this.messageText = text; }
    @Override
    public String toString() { return this.messageText; }
}

All the required classes (MyException, MyEnumObject) exist and are imported into the test file properly. I'm also aware that reflection like this would be ugly and awful for anything except internal testing.

My instinct is that the problem is coming from using the simple List.class, but I can't find a solution for a parameterized version despite trying different syntaxes and Googling, so there's either something else wrong or I'm just missing something. If anyone could shed some light on what's going on here, I would very much appreciate it.

Thanks!





Aucun commentaire:

Enregistrer un commentaire