Halfacht
Halfacht

Reputation: 1034

How to call a method from a generic class as parameter

I've tried to make my code use generics, but I can't seem to get it to work using generics. Any help would be appreciated.

I have 3 classes: Classroom, Course, Teacher

I have the following working code 3 times: (With the small change of the class)

private ObservableList<Classroom> parseClassrooms() {
    // create new Observable List
    ObservableList<Classroom> classrooms = FXCollections.observableArrayList();

    // get lines from file;
    ArrayList<String> arrayList = fhClassroom.read();

    for (String line : arrayList) {
        classrooms.add(Classroom.fromString(line));
    }

    return classrooms;
}

Methods in my Classes:

@Override
public String toString() {
    return name;
}

public static Classroom fromString(String line) {
    return new Classroom(line);
}

Is it possible to make this method generic? and pass the class as parameter?

I would like something like the following:

private ObservableList<T> parseClassrooms(T, FileHelper fh) {
    // create new Observable List
    ObservableList<T> items = FXCollections.observableArrayList();

    // get lines from file;
    ArrayList<String> arrayList = fh.read();

    for (String line : arrayList) {
        items.add(T.fromString(line));
    }

    return items;
}

Upvotes: 0

Views: 74

Answers (1)

Benoit
Benoit

Reputation: 5394

My best attempt:

import java.util.ArrayList;
import java.util.function.Function;

public class Helper {

    public static <T> ObservableList<T> parseItems(Function<String, T> lineToItemFunction, FileHelper fh) {
        // create new Observable List
        ObservableList<T> items = FXCollections.observableArrayList();

        // get lines from file;
        ArrayList<String> arrayList = fh.read();

        for (String line : arrayList) {
            items.add(lineToItemFunction.apply(line));
        }

        return items;
    }
}

And you call it this way:

ObservableList<ClassRoom> classRooms = Helper.parseItems(ClassRoom::fromLine, fileHelper);

Upvotes: 2

Related Questions