I need to have a java method that can be accessed from anywhere within my API but cannot be accessed from the application using the API

I need to have a java method that can be accessed from anywhere within my API but cannot be accessed from the application using the API

Create an interface and expose only that to the public, hiding your implementation. For example:

My implementation (in say, for example, application.jar):

public class Test implements TestInterface {
    public void somePrivateStuff() { }

    public void somePublicStuff() { }
}

Dear world, here is my API (in say, for example, publicAPI.jar):

public interface TestInterface {
    public void somePublicStuff();
}

Other developers would compile against your publicAPI.jar. The runtime implementation would come from your application.jar.

The only way to restrict access to specific classes is to make the method protected or package-private. Both only allow access within the package. I would suggest reformatting your package structure.

I need to have a java method that can be accessed from anywhere within my API but cannot be accessed from the application using the API

Inside the method, you can insert:

Throwable th = new Throwable().fillInStackTrace();
StackTraceElement element = th.getStackTrace()[TEST BETWEEN 3 AND 5];

if (element.getClassName().startsWith(your.package)) {
  // CONTINUE YOUR METHOD.
}
else {
  // USER ACCESSING FROM AN APPLICATION.
  // THROW EXCEPTIONS, SHUTDOWN THE SYSTEM... DO WHAT YOU WANT.
}

On the second line, test between 3, 4 and 5, and see which one returns the correct element.getClassName().

Leave a Reply

Your email address will not be published. Required fields are marked *