[SalesForce] the correct way to type cast a dynamic SObject

I'm trying to get the object type conversion as below. But getting compiler error saying Invalid Type t. Any clue to correct it. Thanks. obj_Name is String and Formobject is SObject.

        Type t = Type.forName(obj_name);
        return (t) FormObject;

Best Answer

You can't cast to a Type that way. We do not have "templates" in our language, so we cannot generate multiple methods from a single source. Simply cast to an SObject, and it will work in most cases.

SObject FormObject = (SObject)Type.forName(obj_name).newInstance();
return FormObject;

You'll still have to cast again to get the SObject into a concrete type. Here's an example you can run in Execute Anonymous:

SObject rec = (SObject)Type.forName('Account').newInstance();
Account a = (Account)rec;

The callee will be responsible for casting the object back in to the desired type.

In Java, we can do something like this:

class SomeClass<T> {
    T buildSomething() {
        T x = new T();
        return x;
    }
}

This doesn't work in Apex Code, because we don't have parameterization of classes. This is something that previously existed in Apex Code, but was pulled for some unknown reason.