[SalesForce] Static method able to be called/executed from class instantiated from type.newInstance() with interface. Expected

When trying to execute a static method from an instance of a class

testMe tmp = New testMe();
tmp.myStaticMethod('a','b');

we get the familiar:

Static method cannot be referenced from a non static context: void myStaticMethod(Id, String)

However if the class implements an interface, instantiating a new instance of that that interface allows us to execute the static method passing in the parameters

Is this expected / documented?

global interface testIt{
    void myStaticMethod(String a, String b);
}

global class testMe implements testIt{

    global static void myStaticMethod(String a, String b){
        system.debug(a + ' - ' + b);
    }

}

The following executes just fine

System.Type apiMethod = Type.forName('ns', 'testMe');
testit tmp = (testit)apiMethod.newInstance();
tmp.myStaticMethod('a','b');

17:03:46.25 (12026653450)|USER_DEBUG|[171]|DEBUG|a – b

I was expecting that the static instance would not be able to be called but it allows me to. If this is expected great, I will go ahead and use it but if it is not expected I would prefer not to package something I cannot reverse….

I suspect it has to do with the interface since the interface method is not static rather the implementation of it is static in the class. To test the theory I tried this and it executed just fine without complaining about the static method

testIt tmp = (testIt)(New testMe());
tmp.myStaticMethod('a','b');

All answers appreciated but especially thankful if there is some documentation that can be pointed to

Best Answer

You shouldn't depend on the behavior. The documentation states:

A class static variable can’t be accessed through an instance of that class. If class MyClass has a static variable myStaticVariable, and myClassInstance is an instance of MyClass, myClassInstance.myStaticVariable is not a legal expression.

You should always declare methods as instance methods, just to be safe.

Related Topic