What is this Java generics notation before a method called?

Viewed 93

I came across some sample code with a generics notation I'm not familiar with:

vertx.eventBus().<JsonObject>consumer("sensor.updates", message -> {
  JsonObject json = message.body();
  ...
});

Note the "<JsonObject>" before the call to consumer().

I understand what it does, that consumer() takes a generic type T and we're telling the compiler to expect a JsonObject in the second parameter. From the EventBus.consumer docs:

<T> MessageConsumer<T> consumer(String address, Handler<Message<T>> handler)

I guess I'm just surprised to see unfamiliar generics syntax after using it for many years. Is there a name for this notation, or any non-obvious behavior I need to be aware of?

1 Answers

Generally Generics has two types, these are

  1. Generics Types
  2. Generics Methods

Generics Types

You can use type parameters in your class or interface. Generics using in Types are called Generics Types.

public interface Container<T> {
    T first();
    T last();
    void add(T data);
    List<T> getAll();
}

public class MyContainer<T> implements Container<T> {
    // Implementations
}

Generics Methods

Type Parameter can also be defined in a method, and those are called Generics Method. You can define Generics in all methods, such as static and instance methods. The question that you asked is Generics Method.

public static <T> void printTwoTimes(T data) {
    // Codes
}  

By taking type parameter in a method, this method can get type abstraction and can be use with various types in type safe way.

This is an official reference about Generics Methods.

https://docs.oracle.com/javase/tutorial/extra/generics/methods.html

Regards

Related