开发者

Java and Type Safety

开发者 https://www.devze.com 2023-04-09 04:39 出处:网络
The MDN JavaScript guide states the following when doing a comparison between Java and JavaScript: Type safety means, for instance, that you can\'t cast a Java integer into an object reference or ac

The MDN JavaScript guide states the following when doing a comparison between Java and JavaScript:

Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes.

Sure, regarding the first part of the above statement, when talking about typing the general concept of type safety revolves around a languages ability to provide some kind of checking that eliminates possible erroneous conditions regarding operations performed with incompatible types (even though the above example is naive considering that in Java you can box primitive int to the reference type Integer).

But, what exactly do they mean by the second part of the statement?

Here there is talk about the JVM's verifier ensuring a level of memory protection - where "arbitary bit patterns cannot be used as an address."

How does the second part of the statement from MDN relate to type safe开发者_如何学Pythonty?


I suspect they mean that you can't cast an arbitrary memory address into a different type, like you can in C.

struct bar_s {
    char foo_s[100];
}

void stuff() {
    int foo = 5;
    bar_s *bar = &foo;
}

Forgive me if the syntax is wrong, my C is rusty. This takes the memory address of foo, assigns it to a pointer to a bar_s struct, which you can then dereference with lots of associated pain. You are treating an area of memory which was originally an int as a bar_s.

In C, there are a number of attack vectors which allow you to overwrite memory with arbitrary information, and have them executed subsequently. See Buffer Overflow

In java, once an Integer, always an Integer[*]. There is also bounds checking on all arrays which help prevent buffer overflows.

[*] Until garbage collection that is.


It means that in Java, there is (in principle) no way to get around how types are identified. In javascript, a type can be inferred based on how the byte sequence that represents a piece of data. In Java, the VM prevents that sort of thing, to ensure that a sequence of bytes that is intended to be a Foo object, can not be seen as a Bar object.

About accessing private members, that means that you can't make a sequence of bytes mean something different than intended by the programmer, to obtain access to something unintended. At runtime, you can't change object foo of type Foo with private member foobar into an object of type Bar, with the same members, but with foobar made public. The type of each object is encoded in the byte code, which is controlled by the VM at runtime.

0

精彩评论

暂无评论...
验证码 换一张
取 消