How to Make Classes Immutable in Groovy

  • google plus

In Brief...

From time to time you might have sensitive data stored in an object that you don't want modified. For example, you might assign a credit limit to a customer that should be treated as a read-only property. To ensure that object data cannot be changed you can mark a class as immutable using the @Immutable annotation.

Instructions

To learn how to make a class immutable in Groovy follow these three steps:

  1. Open your text editor and type in the following lines of Groovy code:
    
    import groovy.transform.*
    @Immutable class Customer {
    	String name
    	String emailAddress
    	int creditLimit
    	public String toString() {
    		"Name: $name Email: $emailAddress Credit Limit: $creditLimit"
    	}	
    }
    def customer = new Customer(name: "Joe New Customer", emailAddress: "joe@SmoothMail.com", creditLimit: 500)
    println("New customer: ${customer}")
    // The following statement will cause an exception at runtime:
    customer.creditLimit=1000
    
    The script defines the Customer class as immutable using the @Immutable annotation. Note the import statement that specifies the package in which the annotation is located. A sample customer is created with a credit limit of $500. An attempt is made to alter the credit limit. At runtime, this will cause a ReadOnlyPropertyException.
  2. Save your file as ImmutableClass.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run Immutable Class script
    The output displays the customer object. Next, the ReadOnlyPropertyException is raised because an attempt was made to alter the credit limit.

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss