项目中有时候会要求通过sObject的Field的type类型返回其对应的基本类型,然后对其进行相关的处理,创建sObject的field可以选择的type类型是固定多的。
上述类型可以转换成几种基本类型:Boolean、Date、Datetime、Double、Integer、String、Time。
1.封装Primitive枚举类:封装基本类型
1 public enum Primitive { 2 TYPE_BOOLEAN, 3 TYPE_DATE, 4 TYPE_DATETIME, 5 TYPE_DOUBLE, 6 TYPE_INTEGER, 7 TYPE_STRING, 8 TYPE_TIMEOFDAY, 9 TYPE_UNKNOW 10 }
2.创建PrimitiveHelper帮助类:通过字段的DataType返回相关的基本类型
1 public without sharing class PrimitiveHelper { 2 3 public static Primitive getPrimitiveTypeByField(String sObjectName,String fieldName) { 4 Schema.DisplayType fieldType = getFieldDisplayType(sObjectName,fieldName); 5 if(fieldType == Schema.Displaytype.BOOLEAN){ 6 return Primitive.TYPE_BOOLEAN; 7 } 8 else if(fieldType == Schema.Displaytype.BASE64 || fieldType == Schema.Displaytype.COMBOBOX || fieldType == Schema.Displaytype.EMAIL || 9 fieldType == Schema.Displaytype.ENCRYPTEDSTRING || fieldType == Schema.Displaytype.ID || fieldType == Schema.Displaytype.MULTIPICKLIST || 10 fieldType == Schema.Displaytype.PHONE || fieldType == Schema.Displaytype.PICKLIST || fieldType == Schema.Displaytype.REFERENCE || 11 fieldType == Schema.Displaytype.STRING || fieldType == Schema.Displaytype.TEXTAREA || fieldType == Schema.Displaytype.URL){ 12 return Primitive.TYPE_STRING; 13 } 14 else if(fieldType == Schema.Displaytype.CURRENCY || fieldType == Schema.Displaytype.DOUBLE || fieldType == Schema.Displaytype.PERCENT){ 15 return Primitive.TYPE_DOUBLE; 16 } 17 else if(fieldType == Schema.Displaytype.INTEGER){ 18 return Primitive.TYPE_INTEGER; 19 } 20 else if(fieldType == Schema.Displaytype.DATE){ 21 return Primitive.TYPE_DATE; 22 } 23 else if(fieldType == Schema.Displaytype.DATETIME){ 24 return Primitive.TYPE_DATETIME; 25 } 26 else { 27 throw new MyException('无对应的基础类型'); 28 } 29 } 30 31 32 private static Schema.DisplayType getFieldDisplayType(String sObjectName,String fieldName) { 33 ListsObjectTypes = Schema.describeSObjects(new String[]{sObjectName}); 34 if(sObjectTypes == null || sObjectTypes.size() == 0) { 35 throw new MyException('无此Object Name'); 36 } 37 Schema.DescribeSObjectResult sObjectDescribeResult = sObjectTypes.get(0); 38 Map objectFieldMap = sObjectDescribeResult.fields.getMap(); 39 Schema.SObjectField objectField = objectFieldMap.get(fieldName); 40 if(objectField == null) { 41 throw new MyException('无此Field Name'); 42 } 43 Schema.DescribeFieldResult fieldResult = objectField.getDescribe(); 44 45 return fieldResult.getType(); 46 } 47 48 private class MyException extends Exception{} 49 }
效果:
1.存在的相关字段的基本类型
2.不存在的字段的结果显示
总结:此篇用于通过sObject的字段来判断此字段属于哪种基本类型,然后可以通过的基本类型对其进行相关操作。有错误的地方欢迎留言。