Reputation: 1517
I'm creating a dynamic query on Grails. The UI will pass a JSON Object that holds all the criteria. I manage to do that:
def criteria = params.criteria
def l = DomainClass.createCriteria().list {
for(int k = 0; k < criteria.names().length(); k++) {
def names = list[x].names()
if(DomainClass.hasProperty(names[k])) {
eq(names[k], list[x][names[k]])
}
}
}
This works already if all the properties of DomainClass
is type String
, but I also use other types such as Long
and Date
so I want to implement something like this:
def criteria = params.criteria
def l = DomainClass.createCriteria().list {
for(int k = 0; k < criteria.names().length(); k++) {
def names = list[x].names()
if(DomainClass.hasProperty(names[k])) {
if(/* DomainClass.getProperty(names[k]).getClass() == Long */) {
// Parse first string to long before actually using it to the criteria
eq(names[k], Long.valueOf(list[x][names[k]]).longValue()))
}
else if(/* DomainClass.getProperty(names[k]).getClass() == Date */) {
// parse first date
...
}
else {
// The default criteria
eq(names[k], list[x][names[k]])
}
}
}
}
But I don't know in Java nor in Groovy what to use to the condition in the if
statements.
Upvotes: 1
Views: 3614
Reputation: 2471
Exact match
new Long(1L).getClass().equals(Long.class)
> true
or
new Long(1L) instanceof Number
> true
new Long(1L) instanceof Long
> true
Your ==
approach (with added .class
), should also work, since it is unlikely, that there are two different Long classes are loaded but I would prefer the equals
way.
new Long(1L).getClass() == Long.class
> true (most likely)
Upvotes: 1
Reputation: 2053
There are a couple of ways that you could approach this
instanceof
or
object.getClass().equals(Float.class);
With your example you could do something similar
if(DomainClass.getProperty(names[k]).getClass().equals(Date.class))
Upvotes: 2