Generic data type conversion method

前端 未结 5 861
走了就别回头了
走了就别回头了 2020-12-25 14:31

This question is in response to another question by opensas: building a generic initializer function in java

From his question it became clear that he needs to conve

5条回答
  •  不思量自难忘°
    2020-12-25 14:58

    I am not aware of any library, however the code is just one line.

    Apart from Date, all boxed primitives have a String construtor, so this method does the trick:

    public static  O convert(I input, Class outputClass) throws Exception {
        return input == null ? null : outputClass.getConstructor(String.class).newInstance(input.toString());
    }
    

    To cater for Dates, you could use instanceof within the method, but I would recommend a separate method, since converting dates is a format- and context-sensitive thing (eg String-->Date parses and uses which format?, Long-->Date sets the time).

    I have deliberately left error/special handling to the reader as an exercise.

提交回复
热议问题