My university professor shared this class with us (it’s essentially a generic parser using Gson):
public abstract class GenericDAO<T> { final Class<T> clase; protected File archivo; public GenericDAO(Class<T> clase, String file) throws Exception { this.clase = clase; this.archivo = new File(file); this.archivo.createNewFile(); } public List<T> getAll(Class<T> clase) throws Exception { List<T> list = new ArrayList<T>(); FileReader f = new FileReader(archivo); BufferedReader b = new BufferedReader(f); Gson g = new Gson(); String line = ""; try { while ((line = b.readLine()) != null && !line.equals("")) { JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(line).getAsJsonObject(); list.add(g.fromJson(jsonObject, clase)); } b.close(); } catch (Exception e) { e.printStackTrace(); return list; } return list; } // a lot of other methods to read/write to json files }
I created a class that inherits from it so I can read a Business from a file:
public class Business extends GenericDAO<Business> { private String name; // a lot of other members // this was automatically generated by Intellij: public Business(Class<Business> clase, String file) throws Exception { super(clase, file); } }
Intellij automatically generated a constructor for it, but I don’t understand it. Why does the constructor has a class as a parameter, do I have to pass an instance of itself to it? That doesn’t make sense.
I would be grateful if you can point me to either some documentation to read through, or explain the pattern my professor is using.
Edit: to sum up, how do I instantiate my business class then? This is throwing an error:
Business client = new Business(Business, "path_to_json_file.json");
Advertisement
Answer
This wouldn’t fit well in a comment: you could use a different style of constructor if you want. Replace this:
// this was automatically generated by Intellij: public Business(Class<Business> clase, String file) throws Exception { super(clase, file); }
With this:
public Business(String file) throws Exception { super( Business.class, file); }
Which I think is more like your instructor may have intended.