jeudi 16 juillet 2015

Call a method based on the object type

I have two helper methods:

public String load(URL url) {...}
public String load(File file) {...}

I want to have a method that calls the appropriate helper method depending on what object type it receives:

public void operate(Object object) {...}

I understand that there is a convoluted way of doing it which is:

public void operate(Object object) {
    String data = null;
    if (object.getClass().equals(File.class)) {
        data = load((File) object);
    }
    if (object.getClass().equals(URL.class)) {
        data = load((URL) object);
    }
    // operate on the data....
}

However, this does not seem elegant and was curious if there was a better way..

Aucun commentaire:

Enregistrer un commentaire