java - 如何为不同的类编写一个接口实现?
问题描述
我想为不同类型的类编写一个实现。
这是interface
:
public interface ResourcesInterface<T> {
T readJsonContent(String fileName/*, maybe there also must be class type?*/);
}
这interface
是Student.class
. 在以下示例中,我尝试读取 JSON 文件并Student.class
从中接收对象:
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;
}
}
因此,我不想interface
为每种类型实现这个,而是使用这样的方法:class
readJsonContent(String)
Student student = readFromJson(fileName, Student.class);
AnotherObject object = readFromJson(fileName, AnotherObject.class);
是否可以以某种方式只编写一种实现?而不是对每个不同的实施interface
多次class
?任何想法如何做到这一点?
解决方案
如果我理解正确,您想要一个能够将 JSON 文件解码为对象的通用方法吗?如果是这样,那么您不需要接口。您所需要的只是创建一个具有如下静态方法的类:
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);
}
}
推荐阅读
- java - 如何在java中打印二维数组中元素的索引号?
- javascript - 如何创建一个调用两个函数来确认登录(电子邮件/密码)信息的验证器函数?
- arrays - 将powershell中的对象重定向到其他函数
- javascript - 为什么在有和没有“new”的情况下调用函数时“this”的工作方式不同
- python - 当我们导入一个模块时,我们在 Python 中有一个方法吗?
- c++ - 如何“平移”(使屏幕字节更小)控制台屏幕以渲染更大的 2d 金字塔?
- ms-access - 旧 Access 数据库无法打印报告
- json - 将整数列表作为参数传递给 Ember transitionTo()?
- r - R ggplot2 geom_smooth 不添加负值
- haskell - 使用统计包从 Haskell 中的高斯采样的最佳方法是什么?