S
S
sanex33392016-01-06 21:02:24
Java
sanex3339, 2016-01-06 21:02:24

How to correctly specify the type of the callback argument without casting?

Let's say there is a callback

private void callback (Map<String, Color> data) {
       Color color = data.get("color");
}

which is passed as an argument to the method
new RenderThreadsController<>(this::callback);
In the method, this callback argument is of type interface
@FunctionalInterface
public interface Callback <T> {
    void callback (Map<String, T> data);
}

And called accordingly
Map<String, T> data = new HashMap<>();
        data.put(
            "color",
            (T) new Color(
                random.nextInt(255),
                random.nextInt(255),
                random.nextInt(255)
            )
        );
this.callback.callback(data);

Accordingly, the question is - is it possible to somehow do this without casting Color to T?
(T) new Color(
                random.nextInt(255),
                random.nextInt(255),
                random.nextInt(255)
            )

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
angry_cellophane, 2016-01-07
@sanex3339

Map<String, T> data = new HashMap<>();
        data.put(
            "color",
            (T) new Color(
                random.nextInt(255),
                random.nextInt(255),
                random.nextInt(255)
            )
        );
this.callback.callback(data);

At this point, the type in the map is known, so there is no point in parametrizing the value type, it is better to explicitly specify the Color type, i.e. Map data = new HashMap<>();
If the map can contain values ​​of different types, then you can use the advice from Joshua Bloch - idlebrains.org/tutorials/java-tutorials/effective-...

O
one pavel, 2016-01-07
@onepavel

in java there is such a thing as Wildcards
<? extends T>
<? super T>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question