Skip to content

Instantly share code, notes, and snippets.

@SpenceDiNicolantonio
Created April 3, 2019 16:52
Show Gist options
  • Save SpenceDiNicolantonio/29cd07bac0be3debf30ec16b99bcbed8 to your computer and use it in GitHub Desktop.
Save SpenceDiNicolantonio/29cd07bac0be3debf30ec16b99bcbed8 to your computer and use it in GitHub Desktop.
[Get instance type in Apex] A hack to determine the type of an instance in Apex #salesforce #apex
/*
* Returns the type of a given object. This is a hack around the fact that we can't access the type of an object.
* @param {Object} obj An object
* @returns {Type} the type of the object
*/
private static Type getType(Object obj) {
String typeName = 'Date';
// Attempt to cast the object to Datetime
// If it succeeds, the object is a date
// If a type exception is thrown, catch it and parse the exception for the actual type
try {
Date d = (Date) obj;
} catch(TypeException te) {
String message = te.getMessage().substringAfter('Invalid conversion from runtime type ');
typeName = message.substringBefore(' to Datetime');
}
return Type.forName(typeName);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment