0
private static User yaml() throws IOException, JsonParseException, JsonMappingException {
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    return mapper.readValue(new File("user.yaml"), User.class);
}

Above code is specific to "User" class

I want to make it generic like this,

private static <T> T yaml() throws IOException, JsonParseException, JsonMappingException {
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    return mapper.readValue(new File("user.yaml"), T.class);
}

But getting error at T.class, Can anyone suggest on this please?

  • Try this : https://stackoverflow.com/questions/3437897/how-to-get-a-class-instance-of-generics-type-t – Cyril Mar 09 '19 at 13:33
  • How do you expect a `yaml()` call to know whether you want a `User`, an `Account` or an `Address`, when it's exactly the same call, with no argument to that method giving a hint? – Ralf Kleberhoff Mar 09 '19 at 14:02

1 Answers1

0

Unfortunately you cannot obtain what you'd like to have. You can, however, submit the Class<T> as an input parameter to yaml(...). You'll also have to consider the file name, as it won't be anymore only user.yaml.

A solution migth be to pass both as arguments

private static <T> T yaml(final Class<T> clazz, final String fileName) throws IOException, JsonParseException, JsonMappingException {
    return MAPPER.readValue(new File(fileName), clazz);
}

I removed ObjectMapper creation from the method, as it is thread-safe and thus can be stored as a static final class field.

LppEdd
  • 20,274
  • 11
  • 84
  • 139
  • Got the solution: private static T yaml(Class generic) throws IOException, JsonParseException, JsonMappingException { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); return (T) mapper.readValue(new File("user.yaml"), generic); } – user11175628 Mar 09 '19 at 13:39
  • @user11175628 that's the same as the one I posted here. I also added the file name as parameter, as it will most likely change. – LppEdd Mar 09 '19 at 13:40