Jack Twain
Jack Twain

Reputation: 6372

Generating reproducible IDs with UUID?

I'm using UUID.randomUUID().getLeastSignificantBits(); to generate unique IDs. However I want to generate the same IDs every time I run the application in order to debug my code. How can I do that?

Edit: thanks to zim-zam I created this class that solves the problem.

public class IDGenerator {
private static Random random = new Random(1);
public static long getID() {
    long id;
    byte[] array = new byte[16];
    random.nextBytes(array);
    id = UUID.nameUUIDFromBytes( array ).getLeastSignificantBits();
    return id;
}
}

Upvotes: 2

Views: 2692

Answers (3)

okrunner
okrunner

Reputation: 3193

I would create my own class which wraps the UUID class and that can accept some kind of flag to determine if it's in debug mode in which case it would return a constant value or "production" mode in which case it would work as expected.

An even cleaner solution would be to define an interface like IRandomUUIDGenerator and have two implementations for it: ConstantUUIDGenerator which you can use for your testing and DefaultRandomUUIDGenerator implementation for your production code. You can then specify in a config file which implementation to use depending on your environment.

Upvotes: 2

instanceof me
instanceof me

Reputation: 39138

Use java.util.Random, providing the same seed.

Upvotes: 1

Zim-Zam O'Pootertoot
Zim-Zam O'Pootertoot

Reputation: 18148

You can use UUID.nameUUIDFromBytes(byte[] bytes) where you get byte[] bytes from a Random or SecureRandom that you seeded

Upvotes: 7

Related Questions