Skip to content

Instantly share code, notes, and snippets.

@alan-morey
Last active January 8, 2016 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alan-morey/0e49ca4563d056f05782 to your computer and use it in GitHub Desktop.
Save alan-morey/0e49ca4563d056f05782 to your computer and use it in GitHub Desktop.
Wrapper for running anonymous code blocks in Salesforce, print() and println() allow you to write messages to a single output stream and have the out rendered to debug log and also in an AlertException. The AlertException is the always thrown at end of execution which ensures that nothing is ever committed to the Database.
public abstract class AnonApp implements MainMethod {
final String[] OUT = new String[0];
public static void run(Type clazz) {
AnonApp app = (AnonApp) clazz.newInstance();
app.run();
}
public void run() {
try {
((MainMethod) this).main();
} finally {
alertOutput();
}
}
protected void println(Object obj) {
print(obj);
OUT.add('\n');
}
protected void print(Object obj) {
OUT.add(String.valueOf(obj));
}
void alertOutput() {
String output = String.join(OUT, '');
System.debug(output);
throw new AlertException(output);
}
class AlertException extends Exception {}
public interface MainMethod {
void main();
}
}
class Main extends AnonApp {
public void main() {
println('foo');
print('bar');
}
}
AnonApp.run(Main.class);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment