简体   繁体   中英

Compiling Java files

I am building an API for my application as a middle layer between model and the controller. The model contains all data and low-level function. I have created a new class for API which uses the model but makes things easier for the user and does not let the user to access the data directly.

Now, I would like to prevent the user from accessing the model and let him to use only the functions from API.

How do I do that?

As far as I believe, this can be simply done by specifying whether the method or variable is private or public . The problem is that I have many static fields for global data. Can I restrict access to static fields so that only private functions of API can access them?

Creating a private static field in a class will ensure that ONLY functions in that class will have access to those fields. Also, if the class is re-instantiated (aka new myClass(); ), those fields will not be recreated; their values will remain intact and global to all instances of myClass.

In addition to the already posted answer:

It depends on what you mean by "restrict access to static fields":

If you want to prevent others from using them directly inadvertently, use the "private" modifier. But remember that one can still access them via reflection if no other countermeasures have bin put into place.

This holds true also for the "static int foo" case if you don't seal the package since one can easily put another class into the same package which will have access again.

If you are building an API, maybe you want to read the book Practical API Design, Confessions of a Java Framework Architect .

A Method Is Better Than a Field It's better to use methods —typically getters and setters— to access fields than to expose them directly.

A Factory Is Better Than a Constructor You facilitate an API's future evolution when you expose a factory method rather than a constructor.

Make Everything Final For the sake of future evolution, it's better to disallow subclassing ... make your class final.

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM