vendredi 9 octobre 2015

Java - Create object from name and call method

I need to write a Java code that, given a class name, create an object of that type and call a method on it.

I used Java.lang.Class.cast(), but this instruction returns an Object, and there isn't the method that I want to run in the Object class (obviously).

I post some code for explain

import java.lang.reflect.*;

public class Loader {
    public static void main(String[] args) throws Exception {

        String className = "Test";
        Class[] arguments = new Class[] { int.class, int.class };
        Class klass = Class.forName(className);

        Constructor constuctor = klass.getConstructor(arguments);
        Object obj = constuctor.newInstance(new Object[] { 10, 20 });
        klass.getClass().cast(obj).Run(); // <----- PROBLEM
        // this works: ((Test)obj).Run();
    }
}

class Test {
    int a, b;
    public Test(int a1, int b1) {
        a = a1; b = b1;
    }

    public void Run() {
        System.out.println("Run...");
        System.out.println(a + " " + b);
    }
}

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire