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.e开发者_如何学Goach { node ->
operation="${node.@operation.text()}"
if(operation.equals(op.create.toString()))
{
query="${node.text()}"
println "$query"
MyQueryClass myQuery=new MyQueryClass (query)
queryl.add(myQuery)
}
}
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
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
node.@operation.text() == '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
精彩评论