Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 am developing a java API. During my development, I keep facing the following issue:

I have two classes in two different packages. Class A in package x, and class B in package y. I need the class A to access a method M defined in class B. Hence, the modifier that should be used for the method M is public. However, I do not want to allow the developer who will use my API in his/her java application to access the method M. The problem is that the method M has a public modifier as I mentioned, and hence anyone can access it within the API or from outside the API. At the same time, if I decrease the modifier level of the method M to protected or private, the class A will not be able to access the method M because it belongs to a different package. How can I solve this problem? Is my only solution to have A and B in the same package?

like image 590
Traveling Salesman Avatar asked Nov 10 '22 07:11

Traveling Salesman


1 Answers

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.

like image 92
martinez314 Avatar answered Nov 15 '22 07:11

martinez314