简体   繁体   中英

How to write one interface implementation for different classes?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM