[英]How to write one interface implementation for different classes?
我想为不同类型的类编写一个实现。
这是interface
:
public interface ResourcesInterface<T> {
T readJsonContent(String fileName/*, maybe there also must be class type?*/);
}
这是Student.class
的interface
实现。 在以下示例中,我尝试读取 JSON 文件并从中接收Student.class
object :
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;
}
}
因此,我不想为每个class
类型实现此interface
,而是想使用readJsonContent(String)
方法,如下所示:
Student student = readFromJson(fileName, Student.class);
AnotherObject object = readFromJson(fileName, AnotherObject.class);
是否可以以某种方式只编写一种实现? 而不是为每个不同的class
多次实现interface
? 任何想法如何做到这一点?
如果我理解正确,您想要一种能够将 JSON 文件解码为 object 的通用方法,对吗? 如果是这样,那么您不需要接口。 您只需要使用 static 方法创建一个 class,如下所示:
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URL;
import java.util.Objects;
public class JsonUtil {
private JsonUtil(){}
public static <T> T readJsonContent(String fileName, Class<T> clazz) {
ObjectMapper objectMapper = new ObjectMapper();
try {
URL path = Objects.requireNonNull(clazz.getResource(fileName));
return objectMapper.readValue(path, clazz);
} catch (IOException ex) {
throw new UncheckedIOException("Json decoding error", ex);
}
}
public static void main(String[] args) {
Student s = JsonUtil.readJsonContent("", Student.class);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.