如何为不同的类编写一个接口实现?

nbnkbykc  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(379)

我想为不同类型的类编写一个实现。
这是 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 ? 你知道怎么做吗?

nsc4cvqm

nsc4cvqm1#

如果我理解正确的话,您想要一个能够将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);
    }
}

相关问题