i want to return class objects but in generic manner. Comsider lot of if conditions and in each i am creating an object of one class; but want to return at last using only one return statement.
How to do that ??
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communityThe easy (but fairly limited) way would be to have your method simply return an Object
type:
Object val = yourMethod();
public Object yourMethod() {
Object returnObject = null;
if(conditionA){
returnObject = new Class1();
} else if(conditionB) {
returnObject = new Class2();
}
return returnObject;
}
However, if you want to return an object of a particular 'blue-print', you might consider using an Interface. This will allow you to define methods so that your implementing classes will implement them so you can call them easily in consuming code. For example:
public interface MyInterface {
void execute();
}
public class Class1 implements MyInterface {
public void execute() {
// do something Class1 specific
}
}
public class Class2 implements MyInterface {
public void execute() {
// do something Class2 specific
}
}
Then, you could change the method above to be a bit more specific:
MyInterface val = yourMethod();
val.execute();
public Object yourMethod() {
MyInterface returnObject = null;
if(conditionA){
returnObject = new Class1();
} else if(conditionB) {
returnObject = new Class2();
}
return returnObject;
}