# Remove Redundant Type Casts
# Description
The rule first searches the next type-cast operation. If the expression is casted to a type which already is exactly the type of the expression, then the type casting expression is removed. Additionally, also parentheses involved in the cast operation will be removed if they are not necessary any more. This rule regards two types as exactly the same only when both types have also exactly the same generic arguments.
# Benefits
This rule increases readability by removing redundant code.
# Tags
Tags
# Code Changes
# Type cast on string literal
Pre
((String)"HelloWorld").charAt(0);
Post
"HelloWorld".charAt(0);
# Type cast on string variable
Pre
String helloWorld = "HelloWorld";
((String)helloWorld).charAt(0);
Post
String helloWorld = "HelloWorld";
helloWorld.charAt(0);
# Type cast on List of String
Pre
List<String> l = new ArrayList<>();
((List<String>)l).add("value1");
Post
List<String> l = new ArrayList<>();
l.add("value1");
# Type cast combined with unnecessary parentheses
Pre
long x = ((((long)((long)((100 + 200L)) + 300))));
Post
long x = ((100 + 200L)) + 300;
# Limitations
# Casting expressions using wild cards
It is not safe to remove type casts containing wild cards (?
). E.g.:
Not Transformed
List<?> l = new ArrayList<>();
((List<?>)l).size();
# Casting lambda expressions to Object
Lambda expressions are not subtypes of Object and therefore implicit casting is not possible. E.g.:
Not Transformed
Object object = (Supplier<String>) () -> "";
Use a Java Refactoring Tool
No license required
You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.
System-wide Refactoring
Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.