Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse does not allow access to static interface method in external jar from another workspace

Tags:

java

eclipse

jar

  • There are two eclipse workspaces, Workspace A and Workspace B.
  • In Workspace A, there is a project with an interface defining a public static method:

    package workspacea;
    
    public interface Foo {
    
      public static String sayHello() {
        return "Hello, world!";
      }
    }
    
  • I then exported the entire project from Workspace A to a *.jar-File, using Export → Java → JAR file and default settings.

  • In Workspace B, a class should access the static method previously defined:

    package workspaceb;
    
    import workspacea.Foo;
    
    public class Bar {
    
      public static void test() {
        String msg = Foo.sayHello();
      }
    }
    
  • The previously exported *.jar from Workspace A is added to the Java Build Path using Project Properties → Java Build Path → Libraries → Add External JARs...

After following these steps, the line Foo.sayHello(); does not compile:

Unresolved compilation problem: 
This static method of interface Foo can only be accessed as Foo.sayHello

From my understanding, it should compile (it recognizes the Foo interface perfectly fine). The funny thing is that it compiles fine if both projects are located in the same workspace (still using the *.jar library and not a project dependency).

Eclipse offers a quick-fix, which has no effect (at least not on the code).

Eclipse quick-fix tool-tip

What is happening here? Why does the code not compile? Is this an Eclipse bug? If so, is there a fix for it?

I am using Luna Service Release 2 (4.4.2) Build 20150219-0600 and used Java 8 in Workspace A, Java 7 in Workspace B.

Additional note: I can only reproduce this by using an interface. Using an abstract class and the same method works.

like image 645
Frithjof Avatar asked Mar 15 '23 07:03

Frithjof


2 Answers

The problem was caused by using a pre-Java-8 version in Workspace B. There is no bug in Eclipse or Java, Java 7 and below just do not support static methods in interfaces. Java just gives a misleading error saying the static method could be referenced, even though it technically cannot be as it is not available in Java 7 or below.

like image 154
Frithjof Avatar answered Apr 06 '23 06:04

Frithjof


I had this happen because I had created a new Maven project, and it had by default set the compiler level to 1.5.

Switched it to 1.8 and resolved this.

like image 39
mtyson Avatar answered Apr 06 '23 06:04

mtyson