scala生成的字节代码如何丢弃已检查的异常? [英] How does scala generated byte code drops the checked exception?

查看:128
本文介绍了scala生成的字节代码如何丢弃已检查的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为应该抛出已检查异常的方法编写字节代码?

If it possible to write byte code for a method that is supposed to throw a checked exception?

例如,除非方法,否则以下Java类不会编译声明它抛出已检查的异常:

For instance the following Java class doesn't compile unless the method declares it throws the checked exception:

public class CheckedExceptionJava {
  public Class<?> testChecked(String s) throws ClassNotFoundException {
    return Class.forName(s);
  }
}

虽然以下Scala等价物(因为Scala没有'已检查异常):

While the following Scala equivalent does ( because Scala doesn't have checked exceptions ) :

class CheckedException { 
    def testChecked( s : String )  = Class.forName( s ) 
}

即使生成的字节码几乎相同:

Even if the bytecode generated are almost identical:

Compiled from "CheckedExceptionJava.java"
public class CheckedExceptionJava extends java.lang.Object{
public CheckedExceptionJava();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public java.lang.Class testChecked(java.lang.String)   throws java.lang.ClassNotFoundException;
  Code:
   0:   aload_1
   1:   invokestatic    #2; //Method java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class;
   4:   areturn

}

Compiled from "CheckedException.scala"
public class CheckedException extends java.lang.Object implements scala.ScalaObject{
public CheckedException();
  Code:
   0:   aload_0
   1:   invokespecial   #24; //Method java/lang/Object."<init>":()V
   4:   return

public java.lang.Class testChecked(java.lang.String);
  Code:
   0:   aload_1
   1:   invokestatic    #11; //Method java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class;
   4:   areturn

}

问题:是否有可能(以及如何)为它生成字节码并不标记它会抛出一个已检查的异常,即使该方法中的代码没有处理它?<​​/ p>

Question: Is it possible ( and how ) to generate bytecode for that doesn't mark it throws a checked exception even if the code inside that method doesn't handle it?

推荐答案

简单。虽然JVM字节码包含有关方法的已检查异常规范,但在执行任何字节码之前运行的字节码验证程序不会检查方法是否实际符合异常规范。您可以编写一个程序来获取现有的JVM字节码并删除所有异常规范,结果字节码将完全有效并且与原始字节码完全相同(禁止反射)。

Simple. While the JVM bytecode includes checked exception specifications on methods, the bytecode verifier that runs before any bytecode is executed specifically doesn't check that the methods actually conform to exception specifications. You could write a program that took existing JVM bytecode and removed all exception specifications, and the resulting bytecode would be perfectly valid and run identically to the original (barring reflection).

这篇关于scala生成的字节代码如何丢弃已检查的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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