TIL: Java stuff

Java Lambda as parameter

First you need an interface

    private interface Ec2Operation {
        void apply(Ec2Client ec2, String... instanceId);
    }

Then declare the operation (note that you don’t need to define “apply”, just use the interface name. “apply” can actually be anything, as you’ll call it later

Ec2Operation startInstance = (ec2, instances) -> {
StartInstancesRequest request = StartInstancesRequest.builder()
.instanceIds(instances)
.build();
ec2.startInstances(request);
};

Then use it with the interface as a signature, call the function you named

private RequestResult executeEc2Operation(Ec2Operation operation) {
    operation.apply(client, instances);
}

Then call the lambda as parameter in a third function

    public RequestResult start() {
        return executeEc2Operation(startInstance);
    }

Having to declare the interface explicitly makes it much more verbose than Javascript. However you get the benefit of a strong type.

Scala and Go’s approach is probably the best of both worlds: you just need to declare the type in the lambda itself.

SSH library for Java

JSCH is the first result in Google. However it hasn’t been updated in along time and doesn’t support newer algorithms.

SSHJ seems to be a more modern choice. It’s on github too!

Leave a Reply

Your email address will not be published. Required fields are marked *