IAmYourFaja
IAmYourFaja

Reputation: 56934

Keyword 'of' in Java

I was reading the source code for a GitHub project (JClouds-Chef) and stumbled across the most peculiar looking Java:

Iterable<Module> modules =
    ImmutableSet.<Module> of(new SshjSshClientModule(), new SLF4JLoggingModule(),
        new EnterpriseConfigurationModule());

What is of? How is this valid Java? Is of a method? If so, where is it defined? Is it some weird, obscure Java operator that is hardly ever used? Is it something weird like a lambda? I'm tearing my hair out trying to figure out where it is, what it does, and where it's defined!

Upvotes: 0

Views: 244

Answers (3)

Kayaman
Kayaman

Reputation: 73568

It's a method of ImmutableSet (from Google Collections) of course. Is the static generic <Module> throwing you off there? It should work without it as well, since it can be inferred from the beginning part, so it could be written as just ImmutableSet.of(...).

Upvotes: 8

Erik Madsen
Erik Madsen

Reputation: 2014

Check the documentation here. It is a generic, static method. This Oracle tutorial can tell you more about those.

Generic static methods allow you to specify that parameter or return types of static methods should be inferred or specified upon calling the method.

An example from the tutorial is the following:

public class Util {
    // Generic static method
    public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {
        return p1.getKey().equals(p2.getKey()) &&
               p1.getValue().equals(p2.getValue());
    }
}

Upvotes: 3

rion18
rion18

Reputation: 1221

It's part of the Google Collections library. He is using the method to get immutable ordered sets.

Upvotes: 0

Related Questions