How to analyze a string that consists of a static method so we can call it?

advertisements

I'm trying to write a function that receives a string that consists of a static method with a string array as an argument.

For example, let's imagine we have this class with a static method:

package com.stack.examples;

public class Example {

   public static void testMethod() {
       System.out.println("method executed");
    }
}

Now, our function would be in another class, as follows:

package com.stack.functions;

public class Functions {

   public void parseCommand(String command) {
      //TODO, this is where my doubts lie
      //The given string is always composed of a sequence of Java identifiers
        //separated by the character ’.’, representing the full qualified name of
          //a Java method (package.class.method)
       command.execute(); //Would this work? Perhaps reflection would be ideal

   }
}

My objective is to parse the string given as an argument in parseCommand so that

parseCommand("com.stack.examples.Example.testMethod()");

actually calls the static method with the given arguments (in this example case, the method would only print out "message executed").


After searching for alternatives to solve this problem, I found that reflection worked out for me:

Static method to be executed:

package test;

public class Example {
    public static void testMethod() {
        System.out.println("method executed");
    }
}

Main Class:

package test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {

    public static void reflectVulnerableMethod(String str) throws ClassNotFoundException, NoSuchMethodException, SecurityException,
                    IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        String[] parts = str.split("\\.");

        String forKlazz = "";
        for (int i=0; i<parts.length -1; i++) {
            if (i != 0){
                forKlazz += '.' + parts[i];
            }
            else forKlazz += parts[i];
        }
        Class<?> klazz = Class.forName(forKlazz);
        Method m = klazz.getMethod(parts[parts.length-1]);

        m.invoke(null);

    }

    public static void main(String[] args) {
        try {
            reflectVulnerableMethod("test.Example.testMethod");
        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException
                | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}