Created
April 3, 2019 16:52
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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