I'm trying to figure out Generics. Let's say I have a Person class, and I want to write a list of persons to a file. How to make the method accept any list and if the list is List of Person, the method will be able to write all its fields to a file.
class PERSON { String name; String surname; public PERSON(String name, String surname) { this.name = name; this.surname = surname; } } class Lesson7 { public <T> void writeToFile(List<T> list) throws Exception{ Path path = Path.of("C:\\Users\\Professional\\IdeaProjects\\Lesson\\src\\FileWr"); String lineFirst = "# Name Surname"; Files.write(path, lineFirst.getBytes(), StandardOpenOption.APPEND); List<String> rows = new ArrayList<>(); int num = 1; for (T t: list) { String line = String.valueOf(num++) + "." + " " + t.name + " " + t.surname + System.lineSeparator(); } Files.write(Path.of("FileWr"), rows); } public static void main(String[] args) throws Exception { PERSON p1 = new PERSON("Christian", "Bale"); PERSON p2 = new PERSON("Leo", "Dicaprio"); List<PERSON> list1 = List.of(p1, p2); Lesson7 l7 = new Lesson7(); l7.writeToFile(list1); } }
Writeablee.g. which adds atoLinemethod or something. Then you can constraint T to implement this interface and simply call thetoLinemethod on any object which is passed towriteToFileTis of typePerson(don't use all caps for class names) then you will know what its fields are and can use them in the write. Otherwise, you don't know, so you can callT.toString()instead and write using that. Were you to want to be writing them the same in all cases, you would have to use reflectiontoStringimplementation and then write the string that this creates to a file. ThetoStringmethod is available in all Java objects, so you would not need to handle different classes differently, but the results in the file of course would vary by the implementation oftoStringin the individual classes.