首页 > 解决方案 > 如何为不同的类编写一个接口实现?

问题描述

我想为不同类型的类编写一个实现。
这是interface

public interface ResourcesInterface<T> {
  T readJsonContent(String fileName/*, maybe there also must be class type?*/);
}

interfaceStudent.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为每种类型实现这个,而是使用这样的方法:classreadJsonContent(String)

Student student = readFromJson(fileName, Student.class);
AnotherObject object = readFromJson(fileName, AnotherObject.class);

是否可以以某种方式只编写一种实现?而不是对每个不同的实施interface多次class?任何想法如何做到这一点?

标签: javainterfaceabstract-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);
    }
}

推荐阅读