Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java between private and protected

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...

like image 801
Jetse Avatar asked Apr 12 '13 10:04

Jetse


1 Answers

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());
}
like image 72
Evgeniy Dorofeev Avatar answered Oct 16 '22 00:10

Evgeniy Dorofeev