Java 8 type conversion and improvements

Source: Internet
Author: User

Casting the type of an object is a bad design. But in some cases, we have no other choice. Java has this function since the day it was born.

I think Java 8 has improved this ancient technology to some extent.

Static transformation

The most commonly used transformation methods in Java are the following:

Static transformation

Object obj; May is an integerif (obj instanceof integer) {    integer objasint = (integer) obj;    Do something with ' objasint '}

The instanceof and transformation operators are used here, and these operators have been incorporated into the language.

The type of object conversion (in this case, integer) must be statically determined at compile time, so we call this transformation a static transformation.

Assuming that obj is not an integer, the test above will fail. Suppose we do the type conversion in whatever way, we get a classcastexception exception. Suppose that obj is a null,intanceof test that fails, but the transition can be passed. Because null can be referenced by whatever type.

Dynamic transformation

There is an uncommon technique, the method of using class. These methods are consistent with the operators above.

Dynamically converted to known types

Object obj; May is an Integerif (Integer.class.isInstance (obj)) {    Integer objasint = Integer.class.cast (obj);    Do something with ' objasint '

Note that the conversion of the type in this example is also determined at compile time. So there is no need to do so.

Dynamic transformation

Object obj; May is an integerclass<t> type =//Could be Integer.classif (type.isinstance (obj)) {    T objastype = Type.cast (o BJ);    Do something with ' Objastype '}

Since the type of conversion is not known at compile time, we call this transformation a dynamic transformation.

The test results for the error type and null transformation are completely consistent with the results of the static transformation.

The transformation of stream and optional is now

It takes two steps to transform a value in Optional or an element in a Stream: In the first step, we need to filter out the type of the error, and then we need to convert it to the target type.

Transformation in the optional

Optional<?> obj; May contain an integeroptional<integer> Objasint = obj        . Filter (integer.class::isinstance)        . Map ( Integer.class::cast);

We need two steps to complete the transformation, which is not a big problem, but I still feel a bit awkward and redundant.

Future (Possible)

I recommend that class's forced transformation method return a Optional or Stream.

Assume that the type of the object being passed is correct. Returns a optional or stream that includes the object.

Otherwise, the returned optional or stream does not include whatever element.

These methods are more trivial to implement:

A new method 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 ();}

We are able to use FLATMAP to complete the filtering and casting steps:

Implementation of Flatmap:

stream<?

> stream; May contain integersstream<integer> streamofints = stream. FlatMap (Integer.class::castintostream);

The wrong instance type or a null reference. It will fail when the instance is tested. So return an empty Optional or Stream. Such a way never throws an ClassCastException exception.

Costs and benefits

How can we measure whether these methods are really practical?

How much code will actually use them?

Can they improve the readability of code for a medium-level developer?

Is it worth saving a line of code?

What is the cost of implementing and maintaining them?

My answer to these questions is: not much. is very few.

So. This is a game with a total of nearly 0. However, I can prove that although the benefits are not much. But it's more than 0.

How do you feel about that? Do you use these methods yourself?

Java 8 type conversion and improvements

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.