问题描述
当我查看 java.util.UUID.fromString
的实现时,我发现它没有检查UUID长度。这有什么特别的原因吗?它只检查用 - 分隔的组件。
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? It only checks the components separated by "-".
String[] components = name.split("-");
if (components.length != 5)
throw new IllegalArgumentException("Invalid UUID string: "+name);
如果长度不是36,它是否也会抛出IllegalArgumentException?
Should it also throw IllegalArgumentException when length is not 36?
目前,如果没有长度检查,如果小于组件长度,则数字会自动添加0,如果更多,则会自动移位。缺点是,如果输入一个缺少数字的UUID字符串,它将被接受为有效并且前缀为0.这很难调试。
Currently, without the length checking, numbers are automatically prepended with 0's if less than the component length or shifted if more. The downside is, if one entered a UUID string with a missing digit, it is accepted as valid and prepended with 0. This is hard to debug.
例如,这12345678-1234-1234-1234-123456789ab变为12345678-1234-1234-1234-0123456789ab。注意添加了'0'?并且12345678-1234-1234-1234-123456789abcd变为12345678-1234-1234-1234-23456789abcd并删除了1。
For example, this "12345678-1234-1234-1234-123456789ab" becomes "12345678-1234-1234-1234-0123456789ab". Notice the '0' added? And this "12345678-1234-1234-1234-123456789abcd" becomes "12345678-1234-1234-1234-23456789abcd" with the '1' removed.
推送此更进一步,字符串1-2-3-4-5也将被视为有效,并变为00000001-0002-0003-0004-000000000005。
To push this even further, the string "1-2-3-4-5" will also be treated as valid and becomes "00000001-0002-0003-0004-000000000005".
编辑:为了澄清我的问题,这是一个错误还是故意遵循一些标准或原则?
To clarify my question, is this a bug or done on purpose to follow some standard or principle?
推荐答案
只有UUID类的原始作者可以告诉你为什么他们选择不检查fromString方法中的组件长度,但我怀疑他们正试图注意:
Only the original authors of the UUID class could tell you why they chose not to check the component lengths in the fromString method, but I suspect they were trying to heed Postel's law:
您可以随时根据这样的正则表达式检查输入:
You can always check the input against a regular expression like this one:
[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}
这篇关于java.util.UUID.fromString没有检查长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!