異なるタイプのクラスに対して1つの実装を作成したいと思います。
これは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);
どういうわけか1つの実装だけを書くことは可能ですか?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);
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加