Dark theme | Light theme

June 3, 2010

Groovy Goodness: Create Class Instance Dynamically

The Class method in Groovy has a newInstance() to dynamically create a new instance of a given class. We can use an Object array or Map as argument if we want to invoke the non-default constructor of the class.

class Blog {
    String name
    String subject
    Blog() {}
    Blog(String name, String subject) { = name
        this.subject = subject

def blog = Blog.newInstance()
assert !, 'Name has no value'
assert !blog.subject, 'Subject has no value'

def blog2 = Blog.newInstance(['mrhaki', 'Groovy'] as Object[])
assert 'mrhaki' ==
assert 'Groovy' == blog2.subject

def blog3 = Blog.newInstance([name:'mrhaki', subject: 'Groovy'])
assert 'mrhaki' ==
assert 'Groovy' == blog3.subject