Namespace, Class, and Variable Name Precedence
Because local variables, class names, and namespaces can all hypothetically use the same identifiers, the Apex parser evaluates expressions in the form of name1.name2.[...].nameN as follows:
- The parser first assumes that
name1is a local variable withname2-nameNas field references. - If the first assumption does not hold true, the parser then assumes that
name1is a class name andname2is a static variable name withname3-nameNas field references. - If the second assumption does not hold true, the parser then assumes that
name1is a namespace name,name2is a class name,name3is a static variable name, andname4-nameNare field references. - If the third assumption does not hold true, the parser reports an error.
If the expression ends with a set of parentheses (for example, name1.name2.[...].nameM.nameN()), the Apex parser evaluates the expression as follows:
-
The parser first assumes that
name1is a local variable withname2-nameMas field references, andnameNas a method invocation. -
If the first assumption does not hold true:
- If the expression contains only two identifiers (
name1.name2()), the parser then assumes thatname1is a class name andname2is a method invocation. - If the expression contains more than two identifiers, the parser then assumes that
name1is a class name,name2is a static variable name withname3-nameMas field references, andnameNis a method invocation.
- If the expression contains only two identifiers (
-
If the second assumption does not hold true, the parser then assumes that
name1is a namespace name,name2is a class name,name3is a static variable name,name4-nameMare field references, andnameNis a method invocation. -
If the third assumption does not hold true, the parser reports an error.
However, with class variables Apex also uses dot notation to reference member variables. Those member variables might refer to other class instances, or they might refer to an sObject which has its own dot notation rules to refer to field names (possibly navigating foreign keys).
Once you enter an sObject field in the expression, the remainder of the expression stays within the sObject domain, that is, sObject fields cannot refer back to Apex expressions.
For instance, if you have the following class:
Then the following expressions are all legal: