I am curious what kind of syntax is Apex method System.runAs(){ } where in curly brackets I can run my code which will be executed as passed user.

I would like to write my own method with that syntax where between braces I can specify my code with some DML Operations and everything will be rolled back. For example:

    insert new Account();

You can't directly do this. While Java does have a syntax for this via anonymous classes, that isn't a language feature of Apex Code. The closest you can get would be to write an interface and implement that in a class, like this:

public class Myclass {
    public interface rollbackable {
        void doSomething();
    public static void rollback(rollbackable item) {
        Savepoint sp = Database.setSavePoint();

Which you'd then implement in other classes:

public class DoSomethingCool implements MyClass.rollbackable {
    public void doSomething() {
        // Do something here

And finally, you'd actually call your method:

MyClass.rollback(new DoSomethingCool());

You could use a try..finally block for this.

try {
  insert new Account();
finally {
  • Thank You for this answer, I know how try catch works, rollback was only example, I would like to create method like runAs() – patryk Jan 31 '17 at 14:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.