4

I am preparing a Android Java Jar which has some public methods. My requirement is that I want to hide certain public methods in the jar, i.e. the developer should not be able to directly (He can in-directly use it through reflection) use these methods using the jar that I provide him/her.

In AOSP, I see this is done using @hide comment, but the same is not working for me.

Please advise me on this.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
user3202934
  • 77
  • 2
  • 9

2 Answers2

3

Make the methods not be public. Or, do not ship the JAR. There is no concept, in a Java JAR, of having things be public yet not be usable.

In AOSP, I see this is done using @hide comment, but the same is not working for me.

The AOSP creates two JARs. One is used at compile time, and it does not contain the @hide-annotated items. That JAR is not included in the APK file. At runtime, a separate JAR, one that does contain the @hide-annotated items, is used. That is possible because Android controls the runtime classpath.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Hi, Can you tell me how Android does this? How Android controls the runtime classpath? In android there are certain hidden methods that some android applications like Settings App can use, but normal app cannot. I am developing a Jar for android and I want similar thing. – user3202934 Jan 29 '15 at 16:34
  • @user3202934: "How Android controls the runtime classpath?" -- it is the one starting up the zygote process that all Dalvik/ART apps are forked from. – CommonsWare Jan 29 '15 at 17:09
2

For methods that you don't want to be accessible to outside, you need to use private (or protected) modifier.

I assume that in your case you want to have some methods defined as public, because this is easy way how you access them inside of your code, perhaps because you need them in different packages.

I don't know how your API is implemented, but to achieve what you want, you will need to change something in design/architecture. You have few possibilities:

  • Define your class as final and methods as protected
  • Expose your API through interfaces and not classes directly
  • Implement facade class which will expose logic. See Facade pattern
  • Implement wrapper classes (that might be also final, and your methods protected). See Wrapper-Decorator
Dario
  • 2,053
  • 21
  • 31