.QL Language Examples

Article Index
.QL Language Examples
Classes

Queries

.QL queries are similar to SQL select statements. This query finds all classes in the package org.jhotdraw and its subpackages:

from Class c
where c.getPackage().getName().matches("org.jhotdraw%")
select c.getPackage(), c

Query Aggregates

.QL also supports aggregates, which allows for queries that gather code metrics. The following query returns the number of lines of code per package:

from Package p, int loc
where p.fromSource()
  and loc = sum(CompilationUnit cu | 
                cu.getPackage() = p | 
                cu.getNumberOfLines())
select p, loc

where the sum aggregate has the syntax

sum(Variables | Condition | Selected Value)

Querying for Possible Errors

You can write queries to catch possible errors. The following query finds compareTo methods that do not have Object as a parameter, and therefore don't override the Object.compareTo method:

from Method m, Class object
where object.hasQualifiedName("java.lang","Object")
  and m.hasName("compareTo")
  and m.hasModifier("public")
  and m.getNumberOfParams() = 1
  and not(m.getAParamType() = object)
select m.getDeclaringType().getPackage(), 
       m.getDeclaringType(),
       m 

Querying for Style Violations

Violations of good programming style are also good candidates for queries. This simple query finds long anonymous classes (over 50 lines):

from AnonymousClass a 
where a.getLocation().getNumberOfLines() > 50 
select a.getEnclosingType().getPackage(), 
       a.getEnclosingType(), 
       a


 


US and other patent applications pending.