0

Recently, Salesforce came out with a critical update to Restrict Reflective Access to Non-Global Constructors in Packages. The update is active in my org. My code uses Type.newInstance. I'm a bit confused as to why my code is not throwing the error as per the description provided by the critical update.

This is the code structure I have :

public abstract class AbstractClass {
  //some methods + abstract methods
}

public class IWillExtendAbstractClass extends AbstractClass {
  //all abstract methods implemented etc
}

Now I execute the following in anonymous window in dev console (expecting an error to show up for instantiating an abstract class)

AbstractClass obj = (AbstractClass) Type.forName('IWillExtendAbstractClass').newInstance();

I thought this line instantiated an abstract class but since it ran, I sense a gap in my understanding. Can someone explain what this line is doing and give an example for when the error message ApexType does not have a no-arg constructor will show up as per the details of this critical update? Where will this critical update impact the most?

1

The IWillExtendAbstractClass implementation is not abstract. From the documentation:

construction of abstract classes or interfaces is no longer allowed even when the type is visible and can be referenced using Type.forName. Such instantiation fails with this message: "ApexType does not have a no-arg constructor" where ApexType is the type you want to create using the Type.newInstance method.

You should get the above mentioned error if you try to instantiate the abstract class instead.

AbstractClass instance;

// below is not abstract
// therefore it does not match
// conditions from documentation
instance = (AbstractClass)Type.forName('IWillExtendAbstractClass').newInstance();

// below is abstract and should throw the error
instance = (AbstractClass)Type.forName('AbstractClass').newInstance();

// can save a few characters
instance = AbstractClass.class.newInstance();
1
  • What does this line mean? AbstractClass obj = (AbstractClass) Type.forName('IWillExtendAbstractClass').newInstance(); Jul 17 '20 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.