Scala error: class file is broken, bad constant po

2020-03-02 04:59发布

问题:

I'm trying to call the Selenium Java libraries from Scala. I'm using Scala IDE (Eclipse), and Scala 2.10.2. What is causing this compiler error?

error while loading Function, class file '/Dev/selenium-2.35.0/libs/guava-
14.0.jar(com/google/common/base/Function.class)' is broken 
(class java.lang.RuntimeException/bad constant pool index: 0 at pos: 479)   

Sometimes I fix broken class file errors by including more jars -- jars that javac would not need to see, but apparently scalac does. But is this case I don't know what other jars I can add.

回答1:

Found the answer. It's caused by this: https://code.google.com/p/guava-libraries/issues/detail?id=1095. The error disappeared when I added the jsr305 jar.



回答2:

RobN's answer is correct, but I thought I'd write a little bit longer answer with my own experiences. This is related to this question and discussions on Guava issues 776 and 1095 mentioned by RobN.

I had this same problem trying to access

com.google.common.io.BaseEncoding.base64()

Eclipse claims the base64 member does not exist and Gradle build produces the error in the question:

[ant:scalac] error: error while loading BaseEncoding, class file 
   '.../guava-16.0.jar(com/google/common/io/BaseEncoding.class)' is broken

The error is caused by optional dependency on some annotations in Guava's pom.xml. As explained in this answer, Java compiler ignores annotations for which corresponding class file is not found, but Scala compiler requires the defitions to compile.

Explicitly adding the dependency that is optional should solve the problem.

In this particular case Guava's pom.xml has following optional dependency and adding the dependency declarations below to your project will solve the problem:

Gradle:

compile 'com.google.code.findbugs:jsr305:2.0.2'

Maven:

<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>2.0.2</version>
</dependency>