Why throw a string into a string?

In an article on Java Java community sites, as an example (for a JPA converter, but this is not relevant, I think) the following method:

public Boolean convertToEntityAttribute(String y) { String val = (String) y; if(val.equals("Y")){ return true; } else { return false; } } 

What is the use of casting String y to String val? Is there a good reason for this?

Original article: What's New in JPA

+5
source share
3 answers

This selection is completely unnecessary. I can imagine what it was before

 public Boolean convertToEntityAttribute(Object y) { String val = (String) y; ... } 

But later, the type of the argument was changed to String , and the author simply forgot to remove the cast.

+13
source

Is there a good reason for this?

Nothing exists 1 .

But flipside is that the Java compiler knows that the type is not needed and optimizes it. Thus, the only “damage” is readability.

For instance.

 [ stephen@blackbox tmp]$ cat Test.java public class Test { public void test (String x) { String s = (String) x; System.out.println(s); } } [ stephen@blackbox tmp]$ javac Test.java [ stephen@blackbox tmp]$ javap -c Test Compiled from "Test.java" public class Test { public Test(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return public void test(java.lang.String); Code: 0: aload_1 1: astore_2 2: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 5: aload_2 6: invokevirtual #3 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 9: return } [ stephen@blackbox tmp]$ 

Statement String s = (String) x; compiled for easy loading and storage; no checkcast .

I would not be surprised if the JIT compiler could optimize the redundant checkcast ... if he saw it.


1 -... in writing. In the source code that was generated, the redundant type can serve to simplify the writing of the source code generator. In the end, the readability of the generated code is largely irrelevant.

+3
source

This excess casting is useless.

Current code can be simplified to

 public Boolean convertToEntityAttribute(String y) { return "Y".equals(y); } 
+2
source

Source: https://habr.com/ru/post/1237569/


All Articles