Java中任何对象的编译时类型与运行时类型之间有什么区别? [英] What is the difference between a compile time type vs run time type for any object in Java?

查看:126
本文介绍了Java中任何对象的编译时类型与运行时类型之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中任何对象的编译时间和运行时间类型之间有什么区别?我正在阅读 Effective Java 书籍,Joshua Bloch提到编译时类型和运行时类型

  //合适的抑制未经检查的警告
public E pop(){
if(size == 0)
throw new EmptyStackException();
// push需要元素为E类型,所以转换是正确的
@SuppressWarnings(unchecked)E result =(E)elements [ - size];
elements [size] = null; //消除过时的引用
返回结果;



$ b $ p
$ b

这里作者正在讨论这些不同类型的类型在数组的上下文中。但通过这个问题,我想了解编译时类型运行时类型对于任何类型的对象的区别Java是一种静态类型的语言,因此编译器将尝试确定所有事物的类型并确保所有事物都是类型安全。不幸的是,静态类型推断本质上是有限的。编译器必须保守,并且无法查看运行时信息。因此,它将无法证明某些代码是类型安全的,即使它是真的。



运行时类型是指运行时变量的实际类型。作为程序员,你希望知道这比编译器更好,所以你可以在知道这样做是安全的时候抑制警告。

例如,考虑下面的例子代码(不会编译)

  public class typetest {
public static void main(String [] args){
Object x = args;
String [] y = x;

System.out.println(y [0])
}
}

变量 x 总是有类型 String [] ,但编译器为'能够弄清楚这一点。因此,将它分配给 y 时需要进行明确的转换。


What is the difference between compile time and run time type of any object in Java ? I am reading Effective Java book and Joshua Bloch mentions about compile time type and run time types of array instances in Item 26 many times mainly to describe that suppressing cast warnings can be safe sometimes.

// Appropriate suppression of unchecked warning
public E pop() {
 if (size == 0)
   throw new EmptyStackException();
   // push requires elements to be of type E, so cast is correct
   @SuppressWarnings("unchecked") E result = (E) elements[--size];
   elements[size] = null; // Eliminate obsolete reference
   return result;
}

Here the author is talking about these different types of types in context of arrays . But through this question I would like to understand the difference between compile time types vs run time types for any type of object .

解决方案

Java is a statically typed language, so the compiler will attempt to determine the types of everything and make sure that everything is type safe. Unfortunately static type inference is inherently limited. The compiler has to be conservative, and is also unable to see runtime information. Therefore, it will be unable to prove that certain code is typesafe, even if it really is.

The run time type refers to the actual type of the variable at runtime. As the programmer, you hopefully know this better than the compiler, so you can suppress warnings when you know that it is safe to do so.

For example, consider the following code (which will not compile)

public class typetest{
    public static void main(String[] args){
        Object x = args;
        String[] y = x;

        System.out.println(y[0])
    }
}

The variable x will always have type String[], but the compiler isn't able to figure this out. Therefore, you need an explicit cast when assigning it to y.

这篇关于Java中任何对象的编译时类型与运行时类型之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆