mardi 1 novembre 2016

Dynamically invoked method returns null

I would like to dynamically invoke chosen method, unfortunately it returns null. When I cast class explicitly and call method, it returns correct value.

/**
 * Result for static call and dynamic invoke of the same function
 * Class: Definition, method: getVersion(), Value: 3.3
 * Class: org.test.classes.Definition, method: getVersion, Value: null
 *
 * @param cls which is instantiated
 * @param method which is invoked
 */
private void callMethodWhichReturnsString(Class cls, Method method) {
    try {
        //problem with invoke of the methods
        stringBuilder.append("Class: Definition, method: getVersion(), Value: ");
        stringBuilder.append(((Definition)data).getVersion());
        stringBuilder.append("<br>");
        stringBuilder.append("Class: ");
        stringBuilder.append(cls.getName());
        stringBuilder.append(", method: ");
        stringBuilder.append(method.getName());
        stringBuilder.append(", Value: ");
        stringBuilder.append(method.invoke(cls.newInstance()));
        stringBuilder.append("<br><br>");
    } catch (IllegalAccessException | InvocationTargetException | InstantiationException ex) {
        stringBuilder.append("Invoke exception!");
    }
}

data is a static variable: private static List data = XMLToObject.convert();

Below is code which shows function for dynamic cast the class and get list of all methods. After I have a list of all methods I call method getVersion (it has id 0).

 private void processClass(Object object) {
     Class current = castDynamic(object);
     try {
          Method[] methods = current.getMethods();
      } catch (NullPointerException e) {
            //something
      }

      callMethodWhichReturnsString(current, methods[0]);
}

Cast class used above:

 private Class castDynamic(Object object) {
    String className = object.getClass().getName();
    try {
        Class cls = Class.forName(className);
        cls.cast(object);
        return cls;
    } catch (ClassNotFoundException e) {
        return null;
    }

Basically, I think that I have done some mistake in invoking the method, but I'm not sure what exactly is wrong.





Aucun commentaire:

Enregistrer un commentaire