vendredi 23 novembre 2018

Instantiate and use an object with only the textual class name in Java

I have several classes in the same package in Java. I want to instantiate objects of these classes from an array that has the class names as strings.

Here is an example of a class I would like to use, they all have the same structure.

class Class1 {

    public String[] firstMethod(){
        String[] data = {"NEW_ITEM"};
        return data;
    }
}

Here is the class I am attemtempting to instantiate them from.

class Main {

    static {
        String[] classes = {"Class1","Class2"};
        for (String cls : classes) {
            try {
                Object o = Class.forName(cls).newInstance();
                o.firstMethod();
            } catch(ClassNotFoundException | IllegalAccessException | InstantiationException ex) {
                System.out.println(ex.toString());
    }
}

My problem is that when I try to call firstMethod() using the object o, I am getting this error.

exit status 1
Main.java:19: error: cannot find symbol
    o.firstMethod();
     ^
symbol:   method firstMethod()
location: variable o of type Object
1 error

I suspect that it is because it is of type Object and not type Class1. I have seen solutions where you typecast the object to the object of the class that you need. However when you typcast, you need to use the name of the class, which is exactly what I am trying to avoid. I need to use the class name as a string.

Does anyone know of a solution where I can call methods with the objects that are created?





Aucun commentaire:

Enregistrer un commentaire