I have a Java class Model
which models some data from my remote database. I want all data models in my project to be able to supply a builder from a Map<String, Object>
instance (in practice, I'm working with SnapshotParser<Model>
parsers with Firestore, but I'll just call getData()
in every model). This should look something like:
public class Model {
private String name;
public Model(String name) { this.name = name; }
public static SnapshotParser<Model> getDocParser() {
return docSnapshot -> {
Map<String, Object> data = docSnapshot.getData();
return new Model(data.getOrDefault("name", "John Doe"));
};
}
}
Note that I'll have several models (Model2
, Model3
...) which will also be required to provide such an interface. To enforce this behavior, I created a DocParserSupplier
generic class for my model classes to implement:
public interface DocParserSupplier<T> {
static SnapshotParser<T> getDocParser();
}
This doesn't work for two reasons (as Android Studio informs me):
static
methods of interfaces must have a default implementation. I can't do that without knowingT
.- I get the "
T
cannot be referenced in static context" error.
If remove the static
keyword from the above interface, I can do what I want but it would require I create an actual instance of the Model
to get the parser. It would work but it makes more sense if the method is static.
Is there a Java way to do what I want?
EDIT: My specific use case is in matching RecyclerView
s to documents in my database. Constructing the FirestoreRecyclerOptions
object requires a parser to convert key-value data to a Model
:
FirestoreRecyclerOptions<Model1> fro1 = new FirestoreRecyclerOptions.Builder<Model1>()
.setQuery(query1, Model1.getDocParser())
.build();
FirestoreRecyclerOptions<Model2> fro2 = new FirestoreRecyclerOptions.Builder<Model2>()
.setQuery(query2, Model2.getDocParser())
.build();