Search code examples
javareflectionenumstalend

Using reflection inside enums but always getting NoSuchMethodException


I'm building a custom component for Talend Open Studio to access a source of data from an application (JIRA) that has a wrapper to get all its data. It exposes an API full of very volatile getters for all its data structure. Since Talend Open Studio supports primitive type only, i usually need to chain several call to get a primitive data (ie. Project.getProjectDetail().getOwner().getName())

But these API often vary and i don't want to change my code every time. So i decided to use an enumeration of methods: when a new field is exposed, i need only to add an element to the enumeration. Something like that:

(i cut most elements to be concise)

public enum JiraProjectField {

    KEY(new String[]{"getKey"}),
    COMPONENTS_NUM(new String[]{"getComponents", "size"}),

    private Method[] m;
    private ArrayList<Class<?>> r;

    private JiraProjectField(String[] methods) {

        this.r = new ArrayList<Class<?>>(methods.length);

        Class<?> initClass = Project.class;
        for(int i=0; i< methods.length; i++){
            try {
                m[i] = initClass.getMethod(methods[0], (Class<?>)null);
                r.add(m[i].getReturnType());
                initClass = m[i].getReturnType();
            } catch (SecurityException e) {
                throw new ExceptionInInitializerError(e.toString());
            } catch (NoSuchMethodException e) {
                throw new ExceptionInInitializerError(e.toString());
            }
        }
}

But I always get a NoSuchMethodException, even if i'm sure the method with that name exists. Is there something i don't know?


Solution

  • I am not sure why you are not using varargs more but you can try

    m[i] = initClass.getMethod(methods[i]);