4
public class A {
    (...)
    public static String staticVar;
}

public class B {
    public B() {
        this.a = new A();
        System.debug( A.staticVar );
        // produces Save error: Class static variable cannot be accessed via object instance
    }
}

This is an ugly side effect of case insensitivity in apex code... Is there a way to force the compiler to see A as the class instead of the instance?

1
  • I doubt there is a way to do so. You will most probably have to change variable name
    – Novarg
    Nov 10, 2014 at 12:47

3 Answers 3

6

looks like you cannot do that; this documentation looks difinitive (emphasis added):

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_static.htm

Class static variables cannot be accessed through an instance of that class. So if class C has a static variable S, and x is an instance of C, then x.S is not a legal expression.

The same is true for instance methods: if M() is a static method then x.M() is not legal. Instead, your code should refer to those static identifiers using the class: C.S and C.M().

If a local variable is named the same as the class name, these static methods and variables are hidden.

1
  • Great assertions Sean, and the docs to back it up :-) Nov 10, 2014 at 16:42
1

If this is in an org with a namespace prefix, you could do

ns.A.staticVar

Otherwise I think you must rename your property and do

this.m_a

etc

0

There is another option, if you have a very common class in your system, eventually someone is going to name a variable or property the same as your class. Since it is an important class, it is likely to have a few static members as well.

Without renaming the property, or trying to convert it to an instance method, you can add an addition class function (to the common one) that just calls the static function. This avoids the problem without obfuscating the rest of the system just to work around this issue.

Since you have a default constructor, this is possible in the main class. Otherwise you could also do this in another helper class.

public class A
    (...)
    public static String staticVar;
    public String staticVar_shadow() {
        return staticVar;
    }
}

public class B {
    public B() {
        this.a = new A();
        System.debug( A.staticVar_shadow() );
    }
}

If you don't have a public A(), then you can also put the shadow function into another helper class that does not have a local "a" variable that interferes.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .