4

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:

Myclass.rollback(){
    insert new Account();
}

2 Answers 2

9

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();
        item.doSomething();
        Database.rollback(sp);
    }
}

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());
1

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .