Skip to content

Instantly share code, notes, and snippets.

@IdelsTak
Created January 2, 2024 13:26
Show Gist options
  • Select an option

  • Save IdelsTak/a63c176312d5be05e4d3d3fda0baac6d to your computer and use it in GitHub Desktop.

Select an option

Save IdelsTak/a63c176312d5be05e4d3d3fda0baac6d to your computer and use it in GitHub Desktop.

Revisions

  1. IdelsTak revised this gist Jan 2, 2024. 1 changed file with 0 additions and 7 deletions.
    7 changes: 0 additions & 7 deletions generate-serialversionuid.md
    Original file line number Diff line number Diff line change
    @@ -3,13 +3,6 @@
    ```bash
    #!/bin/bash

    # Generate serialVersionUID for Java Serializable classes
    # Author: Hiram K.
    # Description: This script generates a positive serialVersionUID for Serializable classes in Java.
    # It utilizes the MD5 hash of the class file to ensure uniqueness.
    # If the generated value is negative, it's adjusted to ensure it's positive.
    # Usage: ./generate_serialVersionUID.sh ClassName

    # Check if class file exists
    if [ ! -f "$1.class" ]; then
    echo "Error: Class file $1.class not found."
  2. IdelsTak created this gist Jan 2, 2024.
    46 changes: 46 additions & 0 deletions generate-serialversionuid.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    # Generate serialVersionUID Script for Java Classes

    ```bash
    #!/bin/bash

    # Generate serialVersionUID for Java Serializable classes
    # Author: Hiram K.
    # Description: This script generates a positive serialVersionUID for Serializable classes in Java.
    # It utilizes the MD5 hash of the class file to ensure uniqueness.
    # If the generated value is negative, it's adjusted to ensure it's positive.
    # Usage: ./generate_serialVersionUID.sh ClassName

    # Check if class file exists
    if [ ! -f "$1.class" ]; then
    echo "Error: Class file $1.class not found."
    exit 1
    fi

    # Generate serialVersionUID using md5 hash
    serialVersionUID=$(md5sum $1.class | cut -d ' ' -f 1)

    # Convert the MD5 hash to a Long value
    longSerialVersionUID=$((16#${serialVersionUID:0:16}))

    # Ensure the Long value is positive
    if [ $longSerialVersionUID -lt 0 ]; then
    longSerialVersionUID=$((longSerialVersionUID + 9223372036854775808))
    fi

    # Print the generated serialVersionUID as Long with 'L' suffix
    echo "Generated serialVersionUID: ${longSerialVersionUID}L"

    ```
    ## How to Use

    - Save the script - copy the script content and save it in a file named `generate_serialVersionUID.sh`, for instance
    - Make it executable - to make the script executable run

    ```shell
    $ chmod +x generate_serialVersionUID.sh
    ```
    - Generate serialVersionUID - navigate to the directory containing your `.class` file and run the script using (replacing `ClassName` with your class name)

    ```shell
    $ ./generate_serialVersionUID.sh ClassName
    ```