Zhro Zhro - 1 year ago 75
Java Question

Can I ask a class what type it needs for a generic?

I have a CompletableFuture whose type depends on the result returned from a message:

public <T> CompletableFuture<T> getFuture(
CompletableMessage message)

Example of some messages:

public class SomeMessageA implements CompletableMessage {
.. // Future is UUID

public class SomeMessageB implements CompletableMessage {
.. // Future is String

public class SomeMessageC implements CompletableMessage {
.. // Future is Integer

I can already explicitly specify the generic:

CompletableFuture<UUID> a = getFuture(new SomeMessageA());
CompletableFuture<String> b = getFuture(new SomeMessageB());
CompletableFuture<Integer> c = getFuture(new SomeMessageC());

The trouble with this is that I won't find if a mistake has been made until runtime.

Is there a way I can acquire the generic type for the future by asking the message for the class of object is being returned?

I can do this in C++ like this:

class SomeMessageA {
typedef int future_t;

SomeMessageA::future_t a;

Can I do something similar in Java or will I always have to reference the documentation for expected type?

Answer Source

The easiest way would be to make CompletableMessage generic too, specifying its return type:

public interface CompletableMessage<T> {

And then inherit specific message with the type:

public class SomeMessageA implements CompletableMessage<Uuid> {

And match the types for getFuture() method:

public <T> CompletableFuture<T> getFuture(CompletableMessage<T> message) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download