10

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

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
Jetse
  • 1,706
  • 2
  • 16
  • 22
  • @mKorbel definitely, OP seems to have put significant effort for it =) – Juvanis Apr 12 '13 at 10:42
  • @mKorbel I expanded this ascii table from [this](http://stackoverflow.com/questions/215497/in-java-whats-the-difference-between-public-default-protected-and-private?rq=1) thread: – Jetse Apr 12 '13 at 10:47
  • but why do you care so much? The only viable reason I can think of is policy enforcement but you can achieve this with some code analysis tool. – akostadinov Apr 12 '13 at 10:49

1 Answers1

6

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());
}
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275