DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Trending

  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • GDPR Compliance With .NET: Securing Data the Right Way
  • Hybrid Cloud vs Multi-Cloud: Choosing the Right Strategy for AI Scalability and Security
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  1. DZone
  2. Coding
  3. Java
  4. Casting in Java 8 (and Beyond?)

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 always been part of Java.

By 
Nicolai Parlog user avatar
Nicolai Parlog
·
Jul. 06, 15 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
21.6K Views

Join the DZone community and get the full member experience.

Join For Free

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:

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:

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.

casting-java-8-and-beyond

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?

Java (programming language)

Published at DZone with permission of Nicolai Parlog, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!