Get SObjectType from 'ObjectName' without using getGlobalDescribe()?
Generically speaking, you can do this:
public static Id getRecordTypeIdForObject(String objName, String recTypeName) {
return ((SObject)Type.forName('Schema', objName)
.newInstance()
)
.getSObjectType()
.getDescribe()
.getRecordTypeInfosByName()
.get(recTypeName)
.getRecordTypeId();
}
You can call it like this:
Id recTypeId = getRecordTypeIdForObject('Account', 'Some Record Type');
This has no error checking, of course, but it should get you started.
Alternatively, assuming you know the type you want in advance:
public static Id getRecordTypeIdForObject(SObjectType objType, String recTypeName) {
return objType.getDescribe()
.getRecordTypeInfosByName()
.get(recTypeName)
.getRecordTypeId();
}
Which would be called like this:
Id recTypeId = getRecordTypeIdForObject(Account.SObjectType, 'Some Record Type');
Depending on how you want to use it, the alternative is to sfdcfox's approach is to cache the global describe in a static variable with lazy instantiation e.g.
global class MyUtils {
private static Map<String, Schema.SObjectType> globalDescribe;
public static Map<String, Schema.SObjectType> getGlobalDescribe() {
if(globalDescribe == null) {
globalDescribe = Schema.getGlobalDescribe();
}
return globalDescribe;
}
public static Id getRecordTypeIdForObject(String objName, String recTypeName) {
return getGlobalDescribe()
.get(objName)
.getDescribe()
.getRecordTypeInfosByName()
.get(recTypeName)
.getRecordTypeId();
}
This would be slow the first time you call it, but then fast on subsequent calls. If you wanted to take it further, you could cache the describe results as well.