Call method of unknown object

Jan Horčička :

I have two ArrayLists - ArrayList1 and ArrayList2. Each of them is filled with objects - Object1 and Object2, respectively. Both of these objects have method 'getText'.

Object1:

public String getText() { return "1";}

Object2:

public String getText() { return "2";}

At certain point I would like to loop through each of these lists using the same method (just with different parameter).

loopThroughList(1)
loopThroughList(2)

What is the syntax if I want to call a method, but I don't know which object it is going to be? This is the code I have so far:

for (Object o : lists.getList(listNumber)) {
    System.out.println(o.getText());
}

It says Cannot resolve method getText. I googled around and found another solution:

for (Object o : lists.getList(listNumber)) {
    System.out.println(o.getClass().getMethod("getText"));
}

But this gives me NoSuchMethodException error. Even though the 'getText' method is public.

EDIT: To get the correct list, I am calling the method 'getList' of a different object (lists) that returns either ArrayList1 or ArrayList2 (depending on the provided parameter).

class Lists

public getList(list) {
    if (list == 1) {
        return ArrayList1;
    }
    else if (list == 2) {
        return ArrayList2;
    }
}
user10367961 :

Define an interface for the getText method

public interface YourInterface {

    String getText();     

}

Implement the interface on the respective classes

public class Object1 implements YourInterface {

    @Override
    public String getText() { 
        return "1";
    }

}

public class Object2 implements YourInterface {

    @Override
    public String getText() { 
        return "2";
    }

}

Modify your getList method to return List<YourInterface>

public static List<YourInterface> getList(int list){
    List<YourInterface> result = new ArrayList<>();
    if(list == 1){
        // your initial type
         List<Object1> firstList = new ArrayList<>();
         result.addAll(firstList);
    } else {
        // your initial type
        List<Object2> secondList = new ArrayList<>();
        result.addAll(secondList);
    }
    return result;
}

Declaration for loopThroughList

public static void loopThroughList(List<YourInterface> list){
    list.forEach(yourInterface -> System.out.println(yourInterface.getText()));
}

Sample usage.

public static void main(String[] args) {
    loopThroughList(getList(1));
    loopThroughList(getList(2));
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111566&siteId=1