How to generate a GUID/UUID in Apex?

How to generate a GUID/UUID in Apex?

On March 14, 2025, Posted by , In Apex, With Comments Off on How to generate a GUID/UUID in Apex?
How to generate a GUIDUUID in Apex

Question:

What is the best way to generate a GUID/UUID in Apex, particularly in the format nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn?

For example, a valid UUID might look like 13219ec0-3a81-44c5-a300-de14b7d0235f. This functionality would be useful in scenarios like assigning unique identifiers to records in triggers.

Answer:

Below is a reusable class in Apex for generating GUIDs/UUIDs. The class uses random number generation to create a unique string formatted according to the requested structure.

Looking for top-tier Salesforce training in Pune? CRS Info Solutions provides expert-led courses, featuring real-time project scenarios to give you practical, hands-on experience. Enroll today for a free demo session and boost your Salesforce skills!

Sample Usage:

You can generate a GUID-like string by creating an MD5 hash of the current timestamp. The timestamp is retrieved using DateTime.now().getTime(), ensuring that each generated string is unique, with a resolution down to 1 millisecond.

if (acct.AccountUuid__c == null) {
    acct.AccountUuid__c = GuidUtil.NewGuid();
}

code explanation: The code checks if the AccountUuid__c field on the acct record is null. If it is, it assigns a newly generated UUID from the GuidUtil.NewGuid() method to ensure the record has a unique identifier.

Apex Class:

global class GuidUtil {

    private static String kHexChars = '0123456789abcdef';

    global static String NewGuid() {
        String returnValue = '';
        Integer nextByte = 0;

        for (Integer i = 0; i < 16; i++) {
            if (i == 4 || i == 6 || i == 8 || i == 10) 
                returnValue += '-';

            nextByte = (Math.round(Math.random() * 255) - 128) & 255;

            if (i == 6) {
                nextByte = nextByte & 15;
                nextByte = nextByte | (4 << 4);
            }

            if (i == 8) {
                nextByte = nextByte & 63;
                nextByte = nextByte | 128;
            }

            returnValue += getCharAtIndex(kHexChars, nextByte >> 4);
            returnValue += getCharAtIndex(kHexChars, nextByte & 15);
        }

        return returnValue;
    }

    global static String getCharAtIndex(String str, Integer index) {
        if (str == null) return null;
        if (str.length() <= 0) return str;    
        if (index == str.length()) return null;    
        return str.substring(index, index + 1);
    }
}

code explanation: The GuidUtil class generates a random UUID in Apex using a loop to construct a 16-byte identifier, inserting hyphens at specific positions to match the UUID format. It ensures compliance with UUID version 4 by setting specific bits and uses a helper method to extract hexadecimal characters for the final string.

This implementation ensures compliance with the UUID version 4 standard, where the sixth octet indicates the UUID version, and the eighth octet indicates the variant. It creates a unique identifier every time it is called.

Summing up

In Apex, a GUID/UUID can be generated using either a timestamp-based or a randomness-based approach. The timestamp method leverages DateTime.now().getTime(), creating a unique 128-bit string hashed with MD5, ensuring uniqueness at the millisecond level but requiring careful timing to avoid duplicates. Alternatively, Crypto.getRandomLong() generates a random long value, which is then hashed using MD5 for higher entropy, though it may be slightly slower due to additional computation. Both methods can format the result into a standard GUID structure using string manipulation techniques like toUpperCase() and insert() to add dashes, ensuring the output follows the typical nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn format.

Jumpstart Your Salesforce Career with Training in Pune

Ready to unlock new career opportunities with Salesforce? CRS Info Solutions offers Salesforce training in Pune, designed to provide you with the skills and knowledge needed to excel in the Salesforce ecosystem. Our courses cover all critical areas, including Salesforce Admin, Developer, and AI modules, with a focus on real-time project-based learning. Led by industry professionals, our training ensures you gain practical experience that prepares you for the challenges of the real world. Whether you’re new to Salesforce or looking to advance your skills, our structured approach helps you become job-ready.

Our Salesforce training in Pune emphasizes hands-on learning, personalized mentorship, and comprehensive resources. You’ll receive detailed class notes, expert guidance for certification, and interview preparation to ensure you’re ready to step into your next Salesforce role.

Don’t miss the chance to accelerate your career—enroll today and join our free demo session to kickstart your Salesforce journey!

Comments are closed.