May I ask why you want to do this?
I ask because there is likely a cleaner way to achieve what you're trying to do.
Polymorphism aims to reduce code with if-statements like this.
Have you considered something like this?
- Build a simple abstract class
public abstract Lease {
public Id recordId { get; private set; }
public Lease(Id recordId) {
this.recordId = recordId;
}
public Date getGreatestMRIVacateDate() {
return Database.Query( getHighestQuery() )
}
private String getHighestQuery() {
return 'SELECT
Id,
Greatest_MRI_Vacate_Date__c
FROM Lease__c
WHERE ' + getObjectIdField() + ' =:recordId';
}
protected abstract String getObjectIdField();
}
- extend the class for your use cases
public Property extends Lease {
public Property(Id recordId) {
super(recordId);
}
private override String getObjectIdField() {
return 'Property__c';
}
}
public Account extends Lease {
public Account(Id recordId) {
super(recordId);
}
private override String getObjectIdField() {
return 'Account__c';
}
}
- Create a Factory class
public class LeaseFactory {
public class TypeException extends Exception();
public static Lease getLease(Id recordId) {
String objType = getSObjectType(recordId);
switch on objType {
when 'Property__c' {
return new Property(recordId);
}
when 'Account__c' {
return new Account(recordId);
}
when else {
throw new TypeException('Unknown Type: ' + recordId);
}
}
}
private static String getSObjectType(Id recordId) {
return Id.valueOf(recordId).getSObjectType().getDescribe().getName();
}
}
- Now you can use it in your code dynamically and cleanly
List<Id> recordIds;
for (Id recordId : recordIds) {
Lease l = LeaseFactory.getLease(recordId);
System.debug( l.getGreatestMRIVacateDate() );
}
This may seem way over engineered (and there's probably a way to make it cleaner), but the advantage of this approach is that if you ever decide add more functionality such as getLowestMRIVacateDate, you only really need to edit the code in one place: the Lease class. The functionality will then filter down to the rest of your classes.
This reduces the amount of times you have to do that if-statement where it figures out which type it is to one time instead of potentially having to do it in every method. It makes the code cleaner, shorter and easier to follow in the long run.
Please note, I'm pretty sure there's a cleaner way still using an interface but I'm tired and don't want to figure it out right now. I recommend watching this:
https://www.youtube.com/watch?v=NU_1StN5Tkk
On another note, if you just have this one method, have you considered SOSL instead of SOQL?
I am not well versed in it but I believe you can do something along the lines of:
FIND :recordId IN (Account__c, Property__c) RETURNING Lease(Id, Greatest_MRI_Vacate_Date__c)
See: https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_sosl_find.htm