I want to write one implementation for different type of classes.
This is interface:
public interface ResourcesInterface<T> {
T readJsonContent(String fileName/*, maybe there also must be class type?*/);
}
This is interface implementation for Student.class.
In the following example I try to read JSON file and receive Student.class object from it:
import com.fasterxml.jackson.databind.ObjectMapper;
public class StudentResources implements ResourcesInterface<Student> {
@Override
public Student readJsonContent(String fileName) {
Student student = new Student();
ObjectMapper objectMapper = new ObjectMapper();
try {
URL path = getClass().getClassLoader().getResource(fileName);
if (path == null) throw new NullPointerException();
student = objectMapper.readValue(path, Student.class);
} catch (IOException exception) {
exception.printStackTrace();
}
return student;
}
}
So instead of implementing this interface for each class type I want to use method readJsonContent(String) something like this:
Student student = readFromJson(fileName, Student.class);
AnotherObject object = readFromJson(fileName, AnotherObject.class);
Is it possible to somehow write only one implementation? Instead of implementing interface multiple times for each different class? Any ideas how to do this?