3

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?

Eric McNeill
  • 1,784
  • 1
  • 18
  • 29
  • It's mentioned in the tutorial here (I'm still looking for an exact answer myself): https://docs.oracle.com/javase/tutorial/java/generics/methods.html – markspace May 04 '21 at 17:14
  • 4
    Ah, I think this is it, it's called a *type witness.* It's used when the type inference system can't distinguish between two or more generic methods and you have to specify which one you want it to use. https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html – markspace May 04 '21 at 17:16
  • 1
    The duplicate link also has an answer that explains that type witnesses were more useful in Java 7, but by Java 8 the type inference system was improved and you hardly ever need a type witness anymore. – markspace May 04 '21 at 17:31
  • Related: https://stackoverflow.com/q/24932177/5515060 – Lino May 04 '21 at 17:42
  • 3
    Thanks @markspace. Type Witness is exactly what I was looking for. I've been writing Java since before generics existed, and it's always somewhat horrifying/pleasing to come across something that makes me say "what the heck is that thing?" – Eric McNeill May 04 '21 at 19:16

1 Answers1

-1

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

Min Lwin
  • 125
  • 7