function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Vladimir BessonovVladimir Bessonov 

how to assign Type dynamically?

How I can define Type T dynamically?

see code below

public string createObject(String ProjectName, String ObjectName, ID ObjectID, CreateObjectData ObjData) {

Project project = ProjectMap.Projects.get(ProjectName);
Type T;
switch on ObjectName {
T = Type.forName('Propulsion_Part__c');
}

when 'Truck' { 
T = Type.forName('Truck_Part__c');
}
}
List<T> PartList = New List<T>(); .... 
Abhishek BansalAbhishek Bansal
Hi Vladimir,

You can use Type.forName and Type.newInstance to create new objects dynamically. See the example below:
sObject newObject = (sObject)Type.forName(ObjectName).newInstance();

//For List
List<SObject> castRecords = (List<SObject>)Type.forName(listType).newInstance();

Let me know if you need any further help on this.

Thanks,
Abhishek Bansal.
Vladimir BessonovVladimir Bessonov
I need a list of my custom objects, not sObject Type shall he defined dynamically. Will the list be casted to my custom type? I see it the instance is casted to sObject I am Newbie to Apex. Please clarify.
Abhishek BansalAbhishek Bansal
Hi Vladimir,

Yes, the list will be casted to your custom object. Please use this statement:
List<SObject> castRecords = (List<SObject>)Type.forName(objectName).newInstance();

Thanks,
Abhishek Bansal.​​​​​​​
Vladimir BessonovVladimir Bessonov
23:44:30:017 USER_DEBUG [33]|DEBUG|An exception occurred: Invalid conversion from runtime type Propulsion_Part__c to List<SObject> 

It looks like the code you proposed tries to cast to sObject. 
Abhishek BansalAbhishek Bansal
Hi Vladimir, 

I think we need to pass the list in order to type cast into a list. You can use the below code:
Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objectName);
String listType = 'List<' + targetType + '>';
List<SObject> castRecords = (List<SObject>)Type.forName(listType).newInstance();

Let me know if you still face any issues.

Thanks,
Abhishek Bansal.
Vladimir BessonovVladimir Bessonov
I think casting is not working as expected. 
I cannot use targetType for a couple of objects I need to create. I add them to the parent object. 


Error  force-app/main/default/classes/CreateObjectForProject.cls  Invalid type: targetType (82:25)
E
rror  force-app/main/default/classes/CreateObjectForProject.cls  Method does not exist or incorrect signature: void add(targetType) from the type List<SObject> (87:32)
ERROR running force:source:push:  Push failed.


also this happens after casting 

00:17:30:159 VARIABLE_ASSIGNMENT [32]|e|"common.apex.runtime.impl.ExecutionException: Attempt to de-reference a null object"|0x25b1c5b6

I don't know. 

But still List<SObject> PartList = (List<SObject>)Type.forName(listType).newInstance(); 
in c++ it would be casting to SObject not to Type.forName(listType).newInstance(). 

Apex is strange
Vladimir BessonovVladimir Bessonov
I might use Factory in this case and hardcode type for each object type I have to create in its own method. 
I would be much easy if List<Type.forName(listType).newInstance()> worked. Aperantly it is not
Abhishek BansalAbhishek Bansal
Hi Vladimir,

Can you paste your complete code where you are getting this error:
Method does not exist or incorrect signature: void add(targetType) from the type List<SObject> (87:32)

I think you are doing something wrong. Just wanted to check. If possible we can coneect on a call and sort this out.

Thanks,
Abhishek Bansal.
Gmail: abhibansal2790@gmail.com
Skype: abhishek.bansal2790
Phone: +917357512102
Vladimir BessonovVladimir Bessonov
/******************************************************************************
* Author: Vladimir Bessonov
* Date: Aug 30, 2020
* Descpription: *
*/
public without sharing class CreateObjectForProject implements ICreateObjectForProject{
private string validateObjectCreateRequest(CreateObjectData data){
string errors='';
if(data.PartNameList.isEmpty())
{
errors=(string.isBlank(errors)?'':errors+',')+'PartNameList is empty, cannot creare Object';
}
if(data.PartMaterialNumberList.isEmpty())
{
errors=(string.isBlank(errors)?'':errors+',')+'PartMaterialNumberList is empty, cannot creare Object';
}
if(data.PartSupplierList.isEmpty())
{
errors=(string.isBlank(errors)?'':errors+',')+'PartSupplierList is empty, cannot creare Object';
}
if(data.PartSupplierPartNumberList.isEmpty())
{
errors=(string.isBlank(errors)?'':errors+',')+'PartSupplierPartNumberList is empty, cannot creare Object';
}
if(String.isBlank(data.APIname))
{
errors=(string.isBlank(errors)?'':errors+',')+'APIname is empty, cannot creare Object';
}
if(String.isBlank(data.Name))
{
errors=(string.isBlank(errors)?'':errors+',')+'Name is empty, cannot creare Object';
}
return errors;
}

public string createObject(String ProjectName, String ObjectName, ID ObjectID, CreateObjectData ObjData) {

//Project project = ProjectMap.Projects.get(ProjectName);
// switch on ObjectName {
// when 'Propulsion' { // when block 1
// Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objectName);
// String listType = 'List<' + targetType + '>';
// List<SObject> castRecords = (List<SObject>)Type.forName(listType).newInstance();
// }
// when 'Truck' { // when block 2
// List<SObject> PL = (List<SObject>)Type.forName('Truck_Part__c').newInstance();
// // T = Type.forName('Truck_Part__c');
// // T = Schema.getGlobalDescribe().get('Truck_part__c').getDescribe() ;
// }
// }
//System.debug('Part List' + PartList);
Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objectName);
String listType = 'List<' + targetType + '>';
List<SObject> PartList = (List<SObject>)Type.forName(listType).newInstance();
System.debug(PartList);
// List<Propulsion_Part__c> PartList = New List<Propulsion_Part__c>();
List<String> PartNames = ObjData.PartNameList;
List<String> PartMaterialNumber = ObjData.PartMaterialNumberList;
List<String> PartSupplierPartNumber = ObjData.PartSupplierPartNumberList;
List<String> PartSupplier = ObjData.PartSupplierList;
for(Integer i=0; i< PartNames.size();i++){
targetType part = new targetType(Propulsion_Set__c=ObjectID, Name = PartNames[i],
Material_Number__c = PartMaterialNumber[i],
Supplier_Part_Number__c = PartSupplierPartNumber[i],
Supplier__c = PartSupplier[i]);
// insert part;
PartList.add(part);
}
Database.SaveResult[] srList = Database.insert(PartList, true);
for(Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
System.debug('Successfully added parts to prop set: ' + ObjectID);
} else {
for(Database.Error objErr : sr.getErrors()) {
System.debug('Error ocurred: ');
System.debug(objErr.getStatusCode() + ' : ' + objErr.getMessage());
System.debug('Prop part affected' + ':'+ objErr.getFields());
}
}
}
return ObjectID;
// add checks and throw exception
// add factory class and simplify CreateObjectForProject - separate create Prop, creat Truck, ext
}

public string createObjectRequest(String ProjectName, String ObjectName, ID ObjectID, CreateObjectData ObjData) {
string errors=validateObjectCreateRequest(ObjData);
if(string.isNotBlank(errors))
{
// TODO: Add class BaseException
// TODO: throw new BaseException(errors);
}
return createObject(ProjectName, ObjectName, ObjectID, ObjData);
}
}

 
Abhishek BansalAbhishek Bansal
Which line is causing the issue?