Home » Java » Core Java » Casting In Java 8 (And Beyond?)

About Nicolai Parlog

Nicolai Parlog
Nicolai is a thirty year old boy, as the narrator would put it, who has found his passion in software development. He constantly reads, thinks, and writes about it, and codes for a living as well as for fun.Nicolai is the editor of SitePoint's Java channel, writes a book about Project Jigsaw, blogs about software development on codefx.org, and is a long-tail contributor to several open source projects. You can hire him for all kinds of things.

Casting In Java 8 (And Beyond?)

Casting an instance to a type reeks of bad design. Still, there are situations where there is no other choice. The ability to do this has hence been part of Java since day one.

I think Java 8 created a need to slightly improve this ancient technique.

Static Casting

The most common way to cast in Java is as follows:

Static Casting

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

This uses the instanceof and cast operators, which are baked into the language. The type to which the instance is cast, in this case Integer, must be statically known at compile time, so let’s call this static casting.

If obj is no Integer, the above test would fail. If we try to cast it anyways, we’d get a ClassCastException. If obj is null, it fails the instanceof test but could be cast because null can be a reference of any type.

Dynamic Casting

A technique I encounter less often uses the methods on Class that correspond to the operators:

Dynamic Casting To Known Type

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:

Dynamic Casting

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.

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:

Casting In 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:

New Methods On Class

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:

FlatMap That Shit

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?

Reference: Casting In Java 8 (And Beyond?) from our JCG partner Nicolai Parlog at the CodeFx blog.
(0 rating, 0 votes)
You need to be a registered member to rate this.
3 Comments Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

3
Leave a Reply

avatar
2 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
soundcloud downloaderNicolai ParlogDavid Kovacs Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
David Kovacs
Guest
David Kovacs

Static cast means converting to a more common type, like Integer to Object. Dynamic cast means the opposite direction, when you need runtime check.

Nicolai Parlog
Guest

Your use of the terms seems to have its root in C++ – the equivalent terms in Java would be widening and narrowing reference conversion. So “dynamic and static casting” are still free to get another meaning. I wrote above why I think they might be appropriate for what I am talking about.

Still, I know that those terms are not very common. I chose them based on the fact that the documentation of Object.isInstance calls itself the “the dynamic equivalent of the Java language instanceof operator”.

soundcloud downloader
Guest

Best and simple code doesn’t need to include comments!!! 15 Years Java coding behind me!