dimanche 24 avril 2016

How to get method parameter classes using Reflection?

For example, if I'm reading through a class C that has a method public void (Foo f) and I'm using reflection, how do I check the method parameter and get the name of the class / object type (Foo)? I tried calling getDeclaredMethods(), then for every method in that array, getParameterTypes(), but that doesn't work. It also gives me a NullPointerException. It lets me do this for fields (e.g. field.getType() and then returns a class) so how can I do that with methods?

 Method[] methods = current.getDeclaredMethods();
            for(Method m: methods){
                numMethods++; //increment # total methods
                Class[] params = m.getParameterTypes();
                if(params.length>0){
                    for(int x = 0; x < params.length; x++){
                        int col = Arrays.asList(classArray).indexOf(params[x]);
                        theData[i][col] = 1;
                    }
                }
                //System.out.println("Current class: " + current.getName());
                //System.out.print(m.toString()+ "\n");
            }

Error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at DesignerAnalyzer.createData(DesignerAnalyzer.java:155)
    at DesignerAnalyzer.loadPackage(DesignerAnalyzer.java:122)
    at DesignerAnalyzer.main(DesignerAnalyzer.java:198)
Java Result: 1





Aucun commentaire:

Enregistrer un commentaire