You can use ClassFromString in OCL when you need to turn a class name held as a string back into a model type so that you can query that type's metadata; this is for modelers working with types rather than instances.
Convert between a type and its string representation
When you work metaâthat is, when an expression examines the structure of your modelâyou may need to move between a type and text.
| Direction | Operator | Result | Example use |
|---|---|---|---|
| Type to string | AsString
|
The type represented as a string | Store or compare a class name as text. |
| String to type | ClassFromString
|
An OclType that you can use to inspect the represented class | Read a tagged value from the represented class. |
Use ClassFromString on a string that represents a model type. The returned value is an OclType, not an instance of that class. This distinction matters: use it to access type-level information such as tagged values, rather than attributes on an object instance.
For the operator syntax and reference example, see Documentation:OCLOperators classfromstring.
Filter subclasses by a class tagged value
A common use is to start with the string values returned by allSubClasses, convert each string to its class type, and then inspect a tagged value on that class.
For example, suppose ComponentSpecification has several subclasses. Mark the subclasses that must be excluded with the tagged value TypeSort set to SKIPTHIS. Use this OCL expression:
ComponentSpecification.allSubClasses->select(x | x.ClassFromString.TaggedValue('TypeSort') <> 'SKIPTHIS')
The expression works as follows:
ComponentSpecification.allSubClassessupplies the subclasses as strings.selectevaluates each subclass string asx.x.ClassFromStringconverts that string to the corresponding class type.TaggedValue('TypeSort')reads theTypeSorttagged value from that class.- The comparison retains every subclass whose value is not
SKIPTHIS.
The result is a collection of subclass strings. It is not a collection of class instances. If you need to perform a further type-level lookup for a selected value, apply ClassFromString to that value again.
Keep the string and tag values consistent
ClassFromString depends on the string identifying a model type. In the filtering example, the tag name and exclusion value must also match the values configured on the classes:
- Use the same tagged-value name in the model and expression, for example
TypeSort. - Use the same exclusion value, for example
SKIPTHIS. - Apply
ClassFromStringbeforeTaggedValue; a string does not expose class metadata until it has been converted to an OclType.
