I am using the Java 9 module system. Below is a simplified version of my problem.
I have defined ClassA (in module com.foo) to implement InterfaceB (in module com.bar). ClassA implements the method print of InterfaceB, which take a parameter of type ClassC (in module com.baz). Below is the code.
// src/a/com/foo/ClassA.java
package com.foo;
import com.bar.InterfaceB;
import com.baz.ClassC;
public class ClassA implements InterfaceB {
@Override
public void print(ClassC obj) {
System.out.println(obj);
}
}
// src/b/com/bar/InterfaceB.java
package com.bar;
import com.baz.ClassC;
public interface InterfaceB {
public void print(ClassC obj);
}
// src/c/com/baz/ClassC.java
package com.baz;
public class ClassC {
@Override
public String toString() {
return "This is a ClassC object";
}
}
The com.baz module does not export anything. So, in order to access ClassC during the compilation of InterfaceB and ClassA, I use the --add-exports flag.
InterfaceB successfully compiles, but when I then try to compile ClassA, I receive the error:
src/a/com/foo/ClassA.java:6: ClassA is not abstract and does not override abstract method print(ClassC) in InterfaceB
Is the compiler somehow using different instances of ClassC? I have a feeling something unexpected is happening with --add-exports.
(As a side note, the reason I'm using --add-exports is that, in my example, com.baz is actually an internal JDK package. I am unable to modify the module settings to export it.)
While there are indeed ways to get the module system to compile your code (you found it already), you will find similar problems at run time when, again, code calling InterfaceB::print can not access ClassC. Again, command line flags can be used to fix that. But they shouldn't!
The module system is trying to tell you something, here: "This modularization is broken!"
If any module outside of com.baz should be allowed to use ClassC, then the package containing it should be exported! This is exactly what exports are for. Other code clearly depends on ClassC and the module system was built to make such dependencies explicit. So unless you're doing this in an exercise to get to know the command line overrides, the real solution is to have com.baz export com.baz.
(If not all modules should see it, consider qualified exports. If reflection is involved, other approaches might be better suited and a new question should be asked.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With