Search code examples
javapolymorphism

Use method without downcasting


I have a method for convert different classes

protected Object convert(String body,Util util) {
        Reader reader = new StringReader(body);
        ObjectMapper objectMapper = new ObjectMapper();
        if(util instanceof MyUtil) {
            // returning a myClass object
            return objectMapper.readValue(reader, myClass.class);
        }
        throw new RuntimeError("Class to converter not exist");
    }

then I am using this method and casting to MyClass

MyClass myclass = (MyClass) converter.convert(util);

how would it look for only one class

protected MyClass convert(String body,Util util) {
        Reader reader = new StringReader(body);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(reader, MyClass.class);
    }
MyClass myclass = converter.convert(util);

Is possible to refactor method to make it more flexible to different return classes and avoid casting?


Solution

  • You can change the signature to match what readValue is doing.

    protected <T> T convert(String body, Class<T> clazz) throws IOException {
        Reader reader = new StringReader(body);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(reader, clazz);
    }
    
    MyClass myclass = app.convert(json, MyClass.class);
    

    This can of course still lead to all kind of exceptions if the input does not match the expected class.