Blankman
Blankman

Reputation: 267370

Is this considered an inline anonymous method?

 public void insert(final String key, final String value) throws Exception {
    execute(new Command(){
      public Void execute(final Keyspace ks) throws Exception {
        ks.insert(key, createColumnPath(COLUMN_NAME), bytes(value));
        return null;
      }
    });
  }

The body of new Command() looks like an inline method?

What is this called, I want to fully understand this.

Upvotes: 5

Views: 763

Answers (4)

Drew Wills
Drew Wills

Reputation: 8446

As stated, it's an anonymous inner class. You most often see this approach as a quick means to implement single-method interfaces.

Languages like Groovy and JavaScript use closures for this sort of thing.

Upvotes: 2

Michael Myers
Michael Myers

Reputation: 192055

It's an anonymous class.

Command is a previously defined interface or class, so this is equivalent to:

public void insert(final String key, final String value) throws Exception {
    class MyCommand implements Command { // or "extends Command"
        public Void execute(final Keyspace ks) throws Exception { 
            ks.insert(key, createColumnPath(COLUMN_NAME), bytes(value)); 
            return null; 
        } 
    }
    execute(new MyCommand());
}

Upvotes: 5

Redlab
Redlab

Reputation: 3118

it's an anonymous inner class. In this case it's most likely an implementation of a Command interface or abstract class.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1504022

It's an anonymous inner class. You're creating a class which derives from the Command class or just implements the Command interface. In this case you're only overriding one method, but you can override more - as well as having extra fields etc.

Java doesn't (currently) have anything which is quite the equivalent of a C# anonymous method, if that's what you were thinking of. An anonymous inner class is probably the closest thing to it though.

Upvotes: 11

Related Questions