Warm tip: This article is reproduced from serverfault.com, please click

How to write one interface implementation for different classes?

发布于 2020-11-28 21:55:01

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?

Questioner
Ilja Tarasovs
Viewed
0
Octavian R. 2020-11-30 00:17:24

If I understood correctly you want a generic method that is able to decode a JSON file to an object right? If so, then you don't need an interface. All you need is to create a class with a static method like this:

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);
    }
}