Java is equivalent to C # "internal"

In Java, leaving the default access modifier (empty), fields become available only to members in the same package. However, this does not prevent others from declaring their classes in one package and then accessing the default fields.

Is there a way in Java to make C # fields equivalent to internal . That is, when I create my library (JAR file), is there no way that others can access these fields outside the JAR? Even when declaring their classes in the same package as my classes.

Here is my declaration in my library:

 package com.my.package; class MyRestrictedClass{ } 



What I'm trying to prevent is to use my library from my project when my jar is added to their build path, for example:

 package com.my.package; //Add their class to my package public class DeveloperClass{ public void main(){ MyRestrictedClass foo = new MyRestrictedClass(); } } 
+6
source share
2 answers

You can seal the package. This prevents people from adding classes to the class path (although you should still protect your banks).

http://docs.oracle.com/javase/tutorial/deployment/jar/sealman.html

Having sealed the jar, you can still compile a class that claims to be in the same package, but when you run it, it will not be able to execute:

 Exception in thread "main" java.lang.SecurityException: sealing violation: can't seal package org.splore.so.access: already loaded at java.net.URLClassLoader.getAndVerifyPackage(URLClassLoader.java:395) at java.net.URLClassLoader.defineClass(URLClassLoader.java:417) at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at org.splore.so.access.AccessTestFromOtherPackage.main(AccessTestFromOtherPackage.java:5) 
+7
source

you can try other access modifiers, such as "protected". However: if someone really wants to access your method, they can use reflections and override the modifier at run time, making it available as they see fit. They can go even further and, for example, remove the final flag and so on. Therefore, it is unsafe to assume that if you use suitable modifiers, no one will be able to access your classes.

I don’t know now, but perhaps there is an annotation that can help your library user understand that they should not use your classes (except for the public API that you provide). Maybe something similar to @depricated or something like that, but I haven't used it myself.

-1
source

Source: https://habr.com/ru/post/957359/


All Articles