AabinGunz
AabinGunz

Reputation: 12347

How to dynamically create a Java class List?

I am using groovy 1.8 where i want to have a list something like this
List<MyQueryClass> queryl=new List<MyQueryClass>()
So that using the below loop i can add more to this list, how can I do that?

def queryxml=new XmlSlurper().parse(QueryProvider.class.getResourceAsStream( '/queries.xml' ))
    queryxml.query.each { node ->
        operation="${[email protected]()}"
        if(operation.equals(op.create.toString()))
        {
            query="${node.text()}"
            println "$query"
            MyQueryClass myQuery=new MyQueryClass (query)
            queryl.add(myQuery)
        }           
    }

Upvotes: 1

Views: 2495

Answers (2)

AabinGunz
AabinGunz

Reputation: 12347

My apologies, I could not convey my question properly.
I figured it out, as I cannot create an instance out of a abstract interface java.util.List

List<MyQueryClass> queryl=new ArrayList<MyQueryClass>() 

does the work. Thanks tim and draganstankovic

Upvotes: 3

tim_yates
tim_yates

Reputation: 171094

You don't give us much to go on, but assuming you have a class:

@groovy.transform.Canonical class MyQuery {
  String queryText
}

And your XML is similar to:

def xml = '''<xml>
  <query operation="create">
    This is q1
  </query>
  <query operation="q2">
    This is q2
  </query>
  <query operation="create">
    This is q3
  </query>
</xml>'''

Then you should be able to use findAll to limit the xml to just the nodes of interest, followed by collect to build up your list of objects like so:

def queryxml = new XmlSlurper().parseText( xml )

List<MyQuery> query = queryxml.query.findAll { node ->  // Filter the nodes
  [email protected]() == 'create'
}.collect { node ->                                     // For each matching node, create a class
  new MyQuery( node.text().trim() )
}

println query

And that prints out:

[MyQuery(This is q1), MyQuery(This is q3)]

PS: The groovy.transform.Canonical annotation is explained here

Upvotes: 1

Related Questions