Consider the below example as my class library project, I need to make CommonClass
accessable for all other classes in the same project (A, B and C) but not accessable to the world (when using the library by another projects), where CommonClass
contains common methods and fields that are used by all other classes within my library, in C# this is solved by using the internal
access modifier on CommonClass
. Is this even possible using Java?
This is an excellent use-case for Java 9's module system. With it, you can export all packages except for com.test.pac4
, prohibiting any project that depends on your library from accessing any classes within that package (unless your users override it via --add-exports
).
To do this, you can create a module-info.java
file in your source directory that contains the following (I recommend changing the module name):
module com.test.project {
exports com.test.pac1;
exports com.test.pac2;
exports com.test.pac3;
}
You'll also need to use requires
for any modules that your project depends on (see: Java 9 Modularity).
If you're using Java 8 or below, then the above solution isn't possible, as the module system was introduced in Java 9.
One workaround on Java 8 is to modify your project hierarchy; you can move every class that accesses CommonClass
into a single package, and then make CommonClass
package-private. This will prevent your library's users from being able to access CommonClass
.
It is assumed that you want to restrict access of class com.sunilos.SecureClass outside your project. It is assumed that base package of your project is "com.sunilos" then you can introduce following code in your class constructor:
public class SecureClass {
final String BASE_PKG = "com.sunilos";
public SecureClass() {
StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
for (int i = 1; i < stElements.length; i++) {
StackTraceElement ste = stElements[i];
if (!ste.getClassName().startsWith(BASE_PKG)) {
throw new RuntimeException("Security Issue");
}
}
}
public String status() {
return "live";
}
}
It will restrict access of your class outside the base package com.sunilos .
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