5

I know we can create a package private class in java. So the class is Internal and only accessible in the specified module:

class MyPackagePrivateClass
{
    ...
}

Now I am developing an android library which i named LibraryA and I wish to use an existing LibraryB in my own LibraryA. How is it possible to prevent user of LibraryA from using the LibraryB directly?

Is there any concept like package private library or anything like that?

Update (For those who ask 'why do I need this?')

In LibraryB there are methods like this:

public QueryBuilder select(String... columns);

But I strongly am of the view that we should use Type-Safe Enum pattern and prevent users from passing strings to these methods(Considering maintenance and refactoring issues). So I decided to wrap those methods in LibraryA:

public TypedQueryBuilder select(Column... columns) {
        queryBuilder = queryBuilder.select(toString(columns));
        return this;
    }

Therefore users of my library should use the Typed methods I provided (Column is a type safe enum here). But if they have access to the original method they may use those instead and I tend to forbid this.

a.toraby
  • 3,232
  • 5
  • 41
  • 73

3 Answers3

1

In Java, with polymorphism, you can't hide a public method of an extended class.

I think that you could archive your goal with Facade Pattern: hide all the complex logic and, in this case, control the access and, if needed, implements some interfaces.

Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73
0

Jigsaw project tries to reach the same goal. But it can take long enough to wait until it would be ported to Android. Until then the best solution IMO is to use package private methods. User will be able to understand that he shouldn't use these methods.

Anyway it's impossible to ultimately forbid library user to do certain things, because one can use reflection or substitute class to get rid of nasty restrictions. But it's possible to encourage user not to do certain things - that's what can be done.

Sergey Fedorov
  • 2,169
  • 1
  • 15
  • 26
-1

Make a jar file out of library B and import it in library A.

https://stackoverflow.com/a/1051705/6897626

Community
  • 1
  • 1
Marcus
  • 1,850
  • 1
  • 12
  • 24
  • 1
    Please read the question carefully. I know how to import a jar file. I want that imported jar file to be accessible just for myself not users of my library. In a normal way you mentioned applications that import my library can also use the imported libraries inside my library. – a.toraby Dec 28 '16 at 08:56