Статьи

Кастинг в Java 8 (и далее?)

Приведение экземпляра к типу пахнет плохим дизайном. Тем не менее, бывают ситуации, когда другого выбора нет. Возможность сделать это, следовательно, была частью Java с самого первого дня.

Я думаю, что в Java 8 возникла необходимость немного улучшить эту древнюю технику.

Статическое литье

Наиболее распространенный способ приведения в Java следующий:

Object obj; // may be an integer
if (obj instanceof Integer) {
Integer objAsInt = (Integer) obj;
// do something with 'objAsInt'
}

При этом используются операторы instanceof и cast, которые запекаются в языке. Тип, к которому приведен экземпляр, в данном случае Integer , должен быть статически известен во время компиляции, поэтому давайте назовем это статическим приведением.

Если obj не является Integer , вышеуказанный тест не пройден. Если мы все равно попытаемся разыграть его, мы получим ClassCastException . Если obj имеет значение null , он не проходит тест instanceof, но может быть приведен, потому что null может быть ссылкой любого типа.

Динамическое Кастинг

Техника, с которой я сталкиваюсь реже, использует методы класса, которые соответствуют операторам:

Object obj; // may be an integer
if (Integer.class.isInstance(obj)) {
Integer objAsInt = Integer.class.cast(obj);
// do something with 'objAsInt'
}

Note that while in this example the class to cast to is also known at compile time, this is not necessarily so:

Object obj; // may be an integer
Class<T> type = // may be Integer.class
if (type.isInstance(obj)) {
T objAsType = type.cast(obj);
// do something with 'objAsType'
}

Because the type is unknown at compile type, we’ll call this dynamic casting.

The outcomes of tests and casts for instances of the wrong type and null references are exactly as for static casting.

литейно-ява-8-и-за

Published by vankarsten under CC-BY-NC 2.0.

Casting In Streams And Optionals

The Present

Casting the value of an Optional or the elements of a Stream is a two-step-process: First we have to filter out instances of the wrong type, then we can cast to the desired one.

With the methods on Class, we do this with method references. Using the example of Optional:

Optional<?> obj; // may contain an Integer
Optional<Integer> objAsInt = obj
.filter(Integer.class::isInstance)
.map(Integer.class::cast);

That we need two steps to do this is no big deal but I feel like it is somewhat awkward and more verbose than necessary.

The Future (Maybe)

I propose to implement casting methods on Class which return an Optional or a Stream. If the passed instance is of the correct type, an Optional or a singleton Stream containing the cast instance would be returned. Otherwise both would be empty.

Implementing these methods is trivial:

public Optional<T> castIntoOptional(Object obj) {
if (isInstance(obj))
return Optional.of((T) obj);
else
Optional.empty();
}

public Stream<T> castIntoStream(Object obj) {
if (isInstance(obj))
return Stream.of((T) obj);
else
Stream.empty();
}

This lets us use flatMap to filter and cast in one step:

Stream<?> stream; // may contain integers
Stream<Integer> streamOfInts = stream.
flatMap(Integer.class::castIntoStream);

Instances of the wrong type or null references would fail the instance test and would lead to an empty Optional or Stream. There would never be a ClassCastException.

Costs And Benefits

What is left to be determined is whether these methods would pull their own weight:

  • How much code could actually use them?
  • Will they improve readability for the average developer?
  • Is saving one line worth it?
  • What are the costs to implement and maintain them?

I’d answer these questions with not much, a little, yes, low. So it’s close to a zero-sum game but I am convinced that there is a small but non-negligible benefit.

What do you think? Do you see yourself using these methods?