- Java UUID
- Версии и варианты UUID :
- Генерация UUID :
- 1. randomUUID ():
- 2. nameUUIDFromBytes ():
- 3. fromString ():
- Сравнение двух UUID :
- Другие методы:
- 1. getLeastSignificantBits () и getMostSignificantBits ():
- 2. вариант () и версия ():
- Работа с UUID на основе времени (v1) :
- Вывод:
- UUID Class
- Remarks
- Constructors
- Properties
- Methods
- Explicit Interface Implementations
- Extension Methods
- Java UUID
- UUID Versions and Variants:
- Generating a UUID:
- 1. randomUUID():
- 2. nameUUIDFromBytes():
- 3. fromString():
- Comparing two UUIDs:
- Other Methods:
- 1. getLeastSignificantBits() And getMostSignificantBits():
- 2. variant() And version():
- Working with a Time-Based UUID (v1):
- Conclusion:
Java UUID
Стандартное представление UUID состоит из шестнадцатеричных цифр:
И имеет 36 символов, которые включают четыре дефиса ‘-‘ .
Класс java.util.UUID в Java представляет неизменный UUID.
Мы можем использовать класс UUID для генерации случайного имени файла, сеанса или идентификатора транзакции. Другое популярное использование UUID для генерации значений первичного ключа в базе данных.
Класс Java UUID имеет метод для управления вариантом Лича-Зальца (вариант 2) . Однако его конструктор позволяет генерировать UUID любого типа:
Версии и варианты UUID :
Вариант определяет расположение UUID . Давайте возьмем пример UUID :
Здесь значение A представляет вариант и определяется его первыми тремя MSB (наиболее значимыми битами):
MSB1 | MSB2 | MSB3 | Вариант | Описание варианта |
---|---|---|---|---|
0 | Икс | Икс | 0 | Зарезервировано для обратной совместимости NCS |
1 | 0 | Икс | 2 | Лич-Зальц |
1 | 1 | 0 | 6 | Зарезервировано, Microsoft Corporation обратная совместимость |
1 | 1 | 7 | Зарезервировано для будущего определения |
Для нас A = 8 (1000) , поэтому первые три MSB равны 100 . Это означает, что наш UUID имеет вариант 2 .
Для варианта 2 UUID существует пять разных версий:
Версия | Описание |
---|---|
v1 | повременной |
v2 | DCE- Безопасность |
v3 и v5 | основанный на имени |
v4 | Случайно сгенерированный UUID |
Генерация UUID :
Давайте рассмотрим методы в классе UUID Java, которые мы можем использовать для генерации UUID :
1. randomUUID ():
Он генерирует псевдослучайный UUID v4, используя криптографически сильный генератор псевдослучайных чисел:
2. nameUUIDFromBytes ():
Мы можем сгенерировать UUID из байтового массива, используя nameUUIDFromBytes () :
Этот метод генерирует UUID v3 (на основе имени).
3. fromString ():
С помощью fromString () мы можем создать UUID из стандартного строкового представления:
Он выдаст исключение IllegalArgumentException для любой неверной строки, переданной в качестве аргумента.
Сравнение двух UUID :
Класс Java UUID реализует Сопоставимый интерфейс. Итак, мы можем использовать метод compareTo () для их сравнения:
Как мы знаем, метод compareTo () возвращает:
- 1: если uuid1 больше, чем uuid2
- 0: если uuid1 = uuid2
- -1: если uuid1 меньше, чем uuid2
При желании мы также можем использовать метод equals () для сравнения.
Другие методы:
Давайте рассмотрим несколько других методов класса Java UUID :
1. getLeastSignificantBits () и getMostSignificantBits ():
Как следует из названия, getLeastSignificantBits () и getMostSignificantBits () возвращают 64 младших и 64 старших значащих бита соответственно :
Оба эти метода возвращают длинное значение.
2. вариант () и версия ():
Мы также можем запросить вариант и версию UUID:
Работа с UUID на основе времени (v1) :
Давайте начнем с добавления зависимости к javauuid -generator в нашем POM :
Обратите внимание, что эта библиотека предоставляет различные типы генераторов UUID.
Чтобы создать основанный на времени UUID , у нас будет:
Другие методы из пакета java.util , которые пригодятся при работе с UUID v1, включают:
1. timestamp (): возвращает значение метки времени, связанное с данным UUID v1 . Этот метод генерирует исключение UnsupportedOperationException при использовании с любыми другими типами UUID .
2. clockSequence (): возвращает 14-битное значение, построенное из поля тактовой последовательности данного UUID . Также будет выброшено исключение UnsupportedOperationException для UUID, отличных от типа v1 .
Вывод:
В этом уроке мы узнали, что такое UUID и его варианты. Мы говорили о разных доступных версиях для варианта типа 2 . Мы также рассмотрели множество методов, предоставляемых классом Java UUID .
Опубликовано на Java Code Geeks с разрешения Шубхры Шриваставы, партнера нашей программы JCG . Смотреть оригинальную статью здесь: Java UUID
Мнения, высказанные участниками Java Code Geeks, являются их собственными.
UUID Class
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
A class that represents an immutable universally unique identifier (UUID).
[Android.Runtime.Register("java/util/UUID", DoNotGenerateAcw=true)] public sealed class UUID : Java.Lang.Object, IDisposable, Java.Interop.IJavaPeerable, Java.IO.ISerializable, Java.Lang.IComparable
[] type UUID = class inherit Object interface ISerializable interface IJavaObject interface IDisposable interface IJavaPeerable interface IComparable
Remarks
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
Constructors
Constructs a new UUID using the specified data.
Properties
Returns the runtime class of this Object .
The handle to the underlying Android instance.
Returns the least significant 64 bits of this UUID’s 128 bit value.
Returns the most significant 64 bits of this UUID’s 128 bit value.
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
Methods
The clock sequence value associated with this UUID.
Creates and returns a copy of this object.
Compares this UUID with the specified UUID.
Indicates whether some other object is «equal to» this one.
Creates a UUID from the string standard representation as described in the #toString method.
Returns a hash code value for the object.
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
Static factory to retrieve a type 3 (name based) UUID based on the specified byte array.
The node value associated with this UUID.
Wakes up a single thread that is waiting on this object’s monitor.
Wakes up all threads that are waiting on this object’s monitor.
Static factory to retrieve a type 4 (pseudo randomly generated) UUID.
The timestamp value associated with this UUID.
Returns a string representation of the object.
The variant number associated with this UUID .
The version number associated with this UUID .
Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.
Causes the current thread to wait until either another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object, or a specified amount of time has elapsed.
Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.
Explicit Interface Implementations
IComparable.CompareTo(Object) | |
IJavaPeerable.Disposed() | (Inherited from Object) |
IJavaPeerable.DisposeUnlessReferenced() | (Inherited from Object) |
IJavaPeerable.Finalized() | (Inherited from Object) |
IJavaPeerable.JniManagedPeerState | (Inherited from Object) |
IJavaPeerable.SetJniIdentityHashCode(Int32) | (Inherited from Object) |
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) | (Inherited from Object) |
IJavaPeerable.SetPeerReference(JniObjectReference) | (Inherited from Object) |
Extension Methods
Performs an Android runtime-checked type conversion.
Java UUID
UUID (Universal Unique Identifier) represents a 128-bit long unique value. It’s also popularly known as GUID (Globally Unique Identifier). The standard representation of UUID is made up of hexadecimal digits:
533a4559-e55c-18b3-8456-555563322002
And has 36 characters that include four hyphens ‘-‘. java.util.UUID class in Java represents an immutable UUID. We can use UUID class for generating a random file name, a session or a transaction id. Another popular usage of UUID is for generating primary key values in the database. Java UUID class has a method for manipulating the Leach-Salz variant (variant 2). However, its constructor allows for generating any type of UUID:
new UUID(long mostSigBits, long leastSigBits)
UUID Versions and Variants:
533a4559-e55c-18b3-8456-555563322002 xxxxxxxx-xxxx-Bxxx-Axxx-xxxxxxxxxxxx
Here, the value of A represents the variant and is determined by its first three MSBs (Most-Significant bits):
MSB1 | MSB2 | MSB3 | Variant | Variant Description |
---|---|---|---|---|
0 | X | X | 0 | Reserved for NCS backward compatibility |
1 | 0 | X | 2 | Leach-Salz |
1 | 1 | 0 | 6 | Reserved, Microsoft Corporation backward compatibility |
1 | 1 | 7 | Reserved for future definition |
For us, A = 8 (1000), so the first three MSBs are 100. That means our UUID has a variant of 2. For variant 2 UUIDs, there’re five different versions:
Version | Description |
---|---|
v1 | time-based |
v2 | DCE- Security |
v3 and v5 | name-based |
v4 | Randomly generated UUID |
Generating a UUID:
1. randomUUID():
It generates a v4 pseudo-random UUID using a cryptographically strong pseudo-random number generator:
UUID uuid = UUID.randomUUID();
2. nameUUIDFromBytes():
byte[] byteArr = ; UUID uuid = UUID.nameUUIDFromBytes(byteArr);
3. fromString():
UUID uuid = UUID.fromString("533a4559-e55c-18b3-2456-555563322002");
It’ll throw an IllegalArgumentException for any invalid string passed in as an argument.
Comparing two UUIDs:
Java UUID class implements Comparable interface. So, we can use the compareTo()method to compare them:
UUID uuid1 = UUID.randomUUID(); UUID uuid2 = UUID.randomUUID(); int result = uuid1.compareTo(uuid2);
- 1: if uuid1 is greater than uuid2
- 0: if uuid1 = uuid2
- -1: if uuid1 is less than that of uuid2
We can optionally use the equals() method for comparison as well.
Other Methods:
Let’s cover a few other methods of the Java UUID class:
1. getLeastSignificantBits() And getMostSignificantBits():
As the name suggests, getLeastSignificantBits() and getMostSignificantBits() return the 64 least-significant and 64 most-significant bits respectively:
UUID uuid = UUID.randomUUID(); long leastSignificantBits = uuid.getLeastSignificantBits(); long mostSignificantBits = uuid.getMostSignificantBits();
Both of these methods return a long value.
2. variant() And version():
We can also query the variant and the version of a UUID:
UUID uuid = UUID.randomUUID(); int variant = uuid.variant(); int version = uuid.version();
Working with a Time-Based UUID (v1):
Let’s start by adding a dependency to java-uuid-generator in our POM:
com.fasterxml.uuid java-uuid-generator 3.1.5
Note that this library provides various types of UUID generators.
To create a time-based UUID, we’ll have:
UUID uuid = Generators.timeBasedGenerator().generate();
Other methods from the java.util package that comes handy when dealing with v1 UUIDs’include:
1. timestamp(): Returns a timestamp value associated with a given v1 UUID. This method will throw a UnsupportedOperationException when used with any other types of UUID.
2. clockSequence(): It returns a 14-bit value constructed from the clock sequence field of a given UUID. It’ll also throw an UnsupportedOperationException for UUIDs other than of type v1.
Conclusion:
In this tutorial, we learned about what a UUID is and its variants. We talked about different available versions for the variant type 2. We also covered a lot of methods exposed by the Java UUID class.
Published on Java Code Geeks with permission by Shubhra Srivastava, partner at our JCG program. See the original article here: Java UUID