I have a class with a method which I want to be accessible only for its child objects, and not for other classes in this package.
Modifier | Class | Package | Subclass | World
————————————+———————+—————————+——————————+———————
public | ✔ | ✔ | ✔ | ✔
————————————+———————+—————————+——————————+———————
protected | ✔ | ✔ | ✔ | ✘
————————————+———————+—————————+——————————+———————
no modifier | ✔ | ✔ | ✘ | ✘
————————————+———————+—————————+——————————+———————
private | ✔ | ✘ | ✘ | ✘
____________+_______+_________+__________+_______
my Modifier | ✔ | ✘ | ✔ | ✘
____________+_______+_________+__________+_______
Is there a workaround to have this kind of modifier?
Maybe there is a way to make a package final, so other programmers can not add any classes into my package?
Or is there a way to get the instance which called the function, and check whether this one is an instance of my super
object?
Or do I just have to leave it, and just use protected, and other programmers might add classes to my package...
1) you cannot create a custom acceess modifier in Java
2) you can seal a package in a jar, see http://docs.oracle.com/javase/tutorial/ext/security/sealing.html
3) you can find the calling class, try
public static void main(String[] args) throws Exception {
xxx();
}
static void xxx() {
Class[] cc = new SecurityManager() {
@Override
protected Class[] getClassContext() {
return super.getClassContext();
}
}.getClassContext();
System.out.println(cc[cc.length - 1].getName());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With