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

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


我有 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;

}


幕布斯6054654
浏览 200回答 1
1回答

陪伴而非守候

我最好的尝试:import java.util.ArrayList;import java.util.function.Function;public class Helper {&nbsp; &nbsp; public static <T> ObservableList<T> parseItems(Function<String, T> lineToItemFunction, FileHelper fh) {&nbsp; &nbsp; &nbsp; &nbsp; // create new Observable List&nbsp; &nbsp; &nbsp; &nbsp; ObservableList<T> items = FXCollections.observableArrayList();&nbsp; &nbsp; &nbsp; &nbsp; // get lines from file;&nbsp; &nbsp; &nbsp; &nbsp; ArrayList<String> arrayList = fh.read();&nbsp; &nbsp; &nbsp; &nbsp; for (String line : arrayList) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; items.add(lineToItemFunction.apply(line));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return items;&nbsp; &nbsp; }}你这样称呼它:ObservableList<ClassRoom> classRooms = Helper.parseItems(ClassRoom::fromLine, fileHelper);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java