java.util.UUID.fromString not checking length

后端 未结 5 1101
深忆病人
深忆病人 2021-01-17 09:34

When I looked into the implementation of java.util.UUID.fromString, I found that it doesn\'t check for the UUID length. Is there any particular reason for this?

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-17 10:12

    The behaviour of UUID.fromString is strange I am not sure if it is a bug or not, but here is what I have been doing to catch those errors.

    public class UUIDUtils {
        public static boolean isValid(String uuid){
            if( uuid == null) return false;
            try {
                // we have to convert to object and back to string because the built in fromString does not have 
                // good validation logic.
                UUID fromStringUUID = UUID.fromString(uuid);
                String toStringUUID = fromStringUUID.toString();
                return toStringUUID.equals(uuid);
            } catch(IllegalArgumentException e) {
                return false;
            }
        }
    }
    

提交回复
热议问题