Reputation: 6290
If i create a project called MyClassA
in a package com/a/b/c
defined as follows:
public class MyClassA {
public static void main(String[] args) {
}
String sayHi() {
return "hi";
}
}
If i export this project as a jar and create another project called MyCassA
in a package com/a/b/c
and import the jar i exported earlier, what is disallowing me from being able to see package protected method sayHi()
?
I have tried this by deleting the first project i exported as a jar. When i tried this i get a compilation error that says the method is not visible.
Upvotes: 0
Views: 89
Reputation: 140427
Not much. Whilst you are not using Java9, with module support enabled.
It is no problem to sneak into existing packages by simply "faking" them. As the other answer outlines you can seal a package via meta data within a jar file. And when you further on think about signing jar files a certain degree of seems to be possible. But I guess even then there might be tricks using class loader magic.
Upvotes: 1
Reputation: 44318
The answers telling you there is nothing that can prevent it are wrong.
You can seal your package. A sealed package is a package that may be defined in one and only one .jar file. The Java runtime will reject any classes defined in that package outside of that .jar file.
Sealing a package is simple. In the containing .jar file’s manifest, add a section for that package, and include a Sealed: true
attribute:
Name: com/a/b/c
Sealed: true
Upvotes: 3
Reputation:
In Java 8 or lower, nothing will disallow you to do that. In other words, it is allowed.
In Java 9, the module system will enforce that packages can only be in a single module
Upvotes: 0