java.util.UUID.fromString not checking length

后端 未结 5 1096
深忆病人
深忆病人 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:16

    Make sure to test against id.equalsIgnoreCase(parsed.toString()) because UUID.fromString(id) returns lower case even if you pass id as upper case.

    @Component
    public class UuidDtoValidator {
    
        public boolean isValidUuid(String id) {
            if (isBlank(id)) {
                return false;
            }
    
            try {
                UUID parsed = UUID.fromString(id);
                if (parsed.equals(new UUID(0, 0))) {
                    return false;
                }
                return id.equalsIgnoreCase(parsed.toString());
            } catch (IllegalArgumentException e) {
                return false;
            }
        }
    }
    

提交回复
热议问题