1

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;

2 Answers 2

1

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.

6
  • I'm storing a Contact in SObject, similarly I need SObject as a Contact object, that's why this is done. And apparently this SObject has to store Objects dynamically, therefore need to cast it this manner. Couldn't help it though. Nov 4, 2016 at 5:43
  • @PasanEeriyagama You can't specifically instantiate an SObject. You can create a record of a specific type and store it in an SObject, but you can't literally make an SObject.
    – sfdcfox
    Nov 4, 2016 at 5:52
  • Wonder why when we have a Type class, and we can't use it for casting in SF. It only allows to create new instances. Nov 7, 2016 at 4:19
  • @PasanEeriyagama Type gives us the ability to make classes dynamically at runtime. It's not as useful as a Reflection class, but it's better than always requiring static type references.
    – sfdcfox
    Nov 7, 2016 at 4:27
  • So is it not possible to cast SObject with values to a specific Object such as Contact, Lead dynamically? I know this is possible by hard coding (Contact), (Lead), etc.. Nov 7, 2016 at 4:35
0

You need to do this

return (task) FormObject;

instead of object instance you need to pass object API name.

You must log in to answer this question.

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