Bytecode features not available in the Java language

后端 未结 9 1452
北恋
北恋 2020-12-04 04:28

Are there currently (Java 6) things you can do in Java bytecode that you can\'t do from within the Java language?

I know both are Turing complete, so read \"can do\"

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 05:07

    Here are some features that can be done in Java bytecode but not in Java source code:

    • Throwing a checked exception from a method without declaring that the method throws it. The checked and unchecked exceptions are a thing which is checked only by the Java compiler, not the JVM. Because of this for example Scala can throw checked exceptions from methods without declaring them. Though with Java generics there is a workaround called sneaky throw.

    • Having two methods in a class that only differ in return type, as already mentioned in Joachim's answer: The Java language specification does not allow two methods in the same class when they differ only in their return type (i.e. same name, same argument list, ...). The JVM specification however, has no such restriction, so a class file can contain two such methods, there's just no way to produce such a class file using the normal Java compiler. There's a nice example/explanation in this answer.

提交回复
热议问题