Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map asType(Class clazz) method



Description

Groovy Map asType(Class clazz) method coerces the map to given object. Map's keys are used to define the public methods and values are treated as implementation.

Syntax

public Object asType(Class clazz)

Parameters

clazz − the target type

Return Value

A proxy of given type which defers call to map's elements

Example - Creating Object from a Map

Following is an example of the usage of this method −

main.groovy

class Student{
   int rollNo
   String name
}

def student1 =[rollNo: 1, name:"Julie"]

// coerce the map to student Object
def student = student1.asType(Student)
println(student.rollNo)
println(student.name)

def student2 =[rollNo: 2, name:"Robert"]
// coerce the map to student Object directly
student = student2 as Student

println(student.rollNo)
println(student.name)

Output

When we run the above program, we will get the following result −

1
Julie
2
Robert

Example - Implementing Interface using a Map

Following is an example of the usage of this method −

main.groovy

interface CustomInterface {
   String method_one()
   String method_two()
}

// Define map as implementation of the interface
def map = [method_one: { "Result of First Method" }, method_two: { "Result of Second Method" }] as CustomInterface

println(map.method_one())
println(map.method_two())

def implementation = map.asType(CustomInterface)

println(implementation.method_one())
println(implementation.method_two())

Output

When we run the above program, we will get the following result −

Result of First Method
Result of Second Method
Result of First Method
Result of Second Method
groovy_maps.htm
Advertisements