繁体   English   中英

显式转换为相同类型

[英]Explicit conversion to the same type

显式转换为相同类型是否会影响性能,还是它们会被编译器过滤而永远不会到达字节码?

例:

int x = 3;
int y = (int) x;

在此类上运行javap -c:

public class SameTypeCastsDemo {

    public static void withoutCasts() {
        int x = 2;
        int y = x;
        System.out.println(y);
    }

    public static void withCast() {
        int x = 2;
        int y = (int) x;
        System.out.println(y);
    }

}

显示字节码看起来相同:

public static void withoutCasts();
  Code:
   0:   iconst_2
   1:   istore_0
   2:   iload_0
   3:   istore_1
   4:   getstatic   #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   7:   iload_1
   8:   invokevirtual   #3; //Method java/io/PrintStream.println:(I)V
   11:  return

public static void withCast();
  Code:
   0:   iconst_2
   1:   istore_0
   2:   iload_0
   3:   istore_1
   4:   getstatic   #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   7:   iload_1
   8:   invokevirtual   #3; //Method java/io/PrintStream.println:(I)V
   11:  return

更新:使用非原始对象引用:

public class SameTypeCastsDemo {
    Integer x;
    Integer y;

    public SameTypeCastsDemo(Integer x, Integer y) {
        this.x = x;
        this.y = y;
    }

    public void print() {
        System.out.println(y);
    }

    public static void withoutCasts() {
        SameTypeCastsDemo x = new SameTypeCastsDemo(2, 3);
        SameTypeCastsDemo y = x;
        y.print();
    }

    public static void withCast() {
        SameTypeCastsDemo x = new SameTypeCastsDemo(2, 3);
        SameTypeCastsDemo y = (SameTypeCastsDemo) x;
        y.print();
    }

}

javap -c SameTypeCastsDemo:

public static void withoutCasts();
  Code:
   0:   new #6; //class SameTypeCastsDemo
   3:   dup
   4:   iconst_2
   5:   invokestatic    #7; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
   8:   iconst_3
   9:   invokestatic    #7; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
   12:  invokespecial   #8; //Method "<init>":(Ljava/lang/Integer;Ljava/lang/Integer;)V
   15:  astore_0
   16:  aload_0
   17:  astore_1
   18:  aload_1
   19:  invokevirtual   #9; //Method print:()V
   22:  return

public static void withCast();
  Code:
   0:   new #6; //class SameTypeCastsDemo
   3:   dup
   4:   iconst_2
   5:   invokestatic    #7; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
   8:   iconst_3
   9:   invokestatic    #7; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
   12:  invokespecial   #8; //Method "<init>":(Ljava/lang/Integer;Ljava/lang/Integer;)V
   15:  astore_0
   16:  aload_0
   17:  astore_1
   18:  aload_1
   19:  invokevirtual   #9; //Method print:()V
   22:  return

Sun将其称为身份转换。

-引用链接-

任何类型都允许从类型到相同类型的转换。

这看似微不足道,但有两个实际后果。 首先,始终允许表达式以所需的类型开头,从而允许简单陈述的规则,即如果只是琐碎的标识转换,则每个表达式都必须进行转换。 其次,它意味着为清楚起见,允许程序包含冗余的强制转换运算符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM