Search code examples
javastringtypesinference

Java how to infer type from data coming from multiple sources


I'm developing a java server that collects data from multiple sensors. These sensors usually return the queried values as string values. In the header it's indicated the data type that the server has to use to cast the received value. These value can be integer, boolean, double, float, and long.

It might happen that the sensors don't provide the "data type description" of the values so: I want to find a way to understand the data type it analyzing the received string.

I was thinking about using REGEX but maybe there are some other ways to do it better. Any suggestion?


Solution

  • There is several approaches to do this. One is try to parse value by different standart java types in proper order i.e.

    Boolean.parseBoolean(s)
    Integer.parseInteger(s)
    Long.parseLong(s)
    ... 
    (and so on)
    

    And catch exception every step Second approach - use apache commons library, there is detection of types i.e.

    BooleanUtils.isBoolean(s)    
    StringUtils.IsNumeric(s)
    StringUtils.IsAlpha(s)