Skip to content

Instantly share code, notes, and snippets.

@sfdcale
Last active July 29, 2018 15:27
Show Gist options
  • Save sfdcale/928dd0ca7b678ff79032f25bb83baac2 to your computer and use it in GitHub Desktop.
Save sfdcale/928dd0ca7b678ff79032f25bb83baac2 to your computer and use it in GitHub Desktop.
DownCasting Failing In Custom APEX Classes

This is related to the question posted on SalesforceSE: https://salesforce.stackexchange.com/questions/226922/downcasting-failing-in-custom-apex-classes

I got curious with one of the answer suggested and wanted to try so updated Term_Segment__c refence to Contact object.

When I am trying this code, it shows error on line numbers 12,13, & 14 in ContactObject class.

Please see this video:

Watch video

Update:

Was able to get rid of the above errors by downcasting to Contact object but it still shows error when downcasting object of instance SubscribeObject to ContactObject.

Please refer to this video: https://vimeo.com/282194861

public class ContactObject extends SubscribeObject {
//Instance
public Contact record;
public Contact oldRecord;
public Contact originalRecord;
public ContactObject(SObject record, SObject oldRecord, Boolean editInPlace) {
// super needs to be the first thing called, if you use it
super(record, oldRecord, editInPlace);
// the accessor methods are inherited, and visible
this.record = (Contact)this.getRecord();
this.oldRecord = (Contact)this.getOldRecord();
this.originalRecord = (Contact)this.getOriginalRecord();
}
//Properties
public Id Id {
get { return record.Id; }
}
public Id lastName {
get { return record.LastName; }
}
public Id firstName {
get { return record.FirstName; }
}
}
public virtual class SubscribeObject {
// Make private so that these variables can't be changed all willy-nilly
// by anything and everything
private SObject record;
private SObject oldRecord;
private SObject originalRecord;
public SubscribeObject(SObject record, SObject oldRecord, Boolean editInPlace) {
this.originalRecord = (Contact) record;
this.oldRecord = (Contact) oldRecord;
if(!editInPlace) { this.record = record.clone(true, true, true, false); }
}
public SubscribeObject() {}
// Make protected accessors for your subclasses
// Apex methods are final by default, meaning they can't be overridden
protected SObject getRecord(){
return this.record;
}
protected SObject getOldRecord(){
return this.oldRecord;
}
protected SObject getOriginalRecord(){
return this.originalRecord;
}
}
//Code to run in developer console to test the above two classes hirerachy.
Contact record = new Contact();
record.LastName = 'Doe';
ContactObject tso = (ContactObject) new SubscribeObject(record,NULL,True); //This line is showing error.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment