Check whether field exists in the object using Salesforce Apex

Check whether field exists in the object using Salesforce Apex

Sample Code:

Set < String > fields = new Set < String >();

for ( Schema.SObjectField objField : Schema.SObjectType.Account.fields.getMap().values() ) {

    fields.add( objField.getDescribe().getName() );

}

for ( Account objAcc : [ SELECT Id, Name, Industry FROM Account LIMIT 1 ] ) {

    if ( fields.contains( 'Name' ) ) {

        System.debug( ( String ) objAcc.get( 'Name' ) );

    }

    if ( fields.contains( 'Invalid_Field' ) ) {

        System.debug( ( String ) objAcc.get( 'Invalid_Field' ) );

    } else {

        System.debug( 'Field not found' );

    }

}

Output:

Leave a Reply