在Salesforce Apex中动态获取SObject信息

以下代码介绍了如何使用Salesforce Apex动态获取SObject信息.


public with sharing class ObjectViewerController {
        
        public void viewObject(String objectName) {
                try {
                        System.Debug('Start');
                        
                        SObjectType objectType = Schema.getGlobalDescribe().get(objectName);
                        Schema.DescribeSObjectResult objectDescribe = objectType.getDescribe(); 
                        Map fieldMap = objectDescribe.fields.getMap();
                        Set fieldNames = fieldMap.keySet();
                        for (String fieldName : fieldNames) {
                                Schema.SObjectField field = fieldMap.get(fieldName);
                                Schema.DescribeFieldResult fieldDescribe = field.getDescribe();
                                System.Debug('field name:' + fieldDescribe.getName());
                                System.Debug('field isNillable:' + fieldDescribe.isNillable());
                        }
                } catch (Exception ex) {
                        ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'Error occured while viewing object:' + ex.getMessage());
            ApexPages.addMessage(errorMessage);
                }
        }

        
        public void viewObject() {
                viewObject('Account');
        }
}

你可能感兴趣的:(salesforce)