如何从泛型类作为参数调用方法

时间:2018-10-22 12:09:23

标签: java generics

我试图使我的代码使用泛型,但是我似乎无法使其使用泛型。任何帮助将不胜感激。

我有3个班级:教室,课程,老师

我有3次以下工作代码:(仅更改了类)

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;
}

我班上的方法

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

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

是否可以使此方法通用?并将类作为参数传递?

我想要以下内容:

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;
}

1 个答案:

答案 0 :(得分:2)

我的最佳尝试:

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;
    }
}

您这样称呼:

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