In twitter, Sébastien Mosser raised the question of how to execute OCL expressions on plain Java classes. As you may know, we can use EMFQuery to query EObjects using OCL expressions as filters as shown in this example (taken from this tutorial) where we select all objects of the Writer class having written books in two or more different categories.
Resource myResource = ... // get the resource
OCL ocl = org.eclipse.ocl.ecore.OCL.newInstance();
Condition condition = new BooleanOCLCondition(
ocl.getEnvironment(),
"self.books->collect(b : Book | b.category)->asSet()->size() > 2",
EXTLibraryPackage.Literals.WRITER);
SELECT statement = new SELECT(SELECT.UNBOUNDED, false,
new FROM(myResource.getContents()), new WHERE(condition),
new NullProgressMonitor());
IQueryResult results = statement.execute();
// do something with the results
selectInEditor(results);
This is good as long as we work within the EMF framework but what about using OCL as an internal DSL embedded in Java? Do you know any tool that would help us with that?
(I do know tools that translate OCL to native Java methods but they do that as part of a code-generation process, they do not allow mixing OCL as part of the Java program itself).
Suggestions very much appreciated!
ICREA Research Professor at Internet Interdisciplinary Institute (UOC). Leader of the SOM Research Lab focusing on the broad area of systems and software engineering. Home page.
Loathe as I am to suggest it, you might want to look at Xtend/Xbase which have a number of OCL-like externsions that then integrate within Java and Java-like Eclipse tooling.
Eclipse OCL has an aspirational Bugzilla to make integration of OCL as easy as Xbase, but I don’t see it being fulfilled any time soon.
Executing OCL on Java classes is certainly possible since the Java reflection API allows the type system to discovered and a metamodel created, provided your favourite OCL tooling supports a diversity of metamodel dialects.