how to restrict protected method access to only subclasses
java
Solution
Easy: Remove all other classes from the package, leaving only your base class there.
That will mean the only classes that can access your class are from another package.
In the case that another library copies your package name, you could easily check the package of the caller and assert that it isn't the same as yours:
if (getClass().getPackage().equals(MyBaseClass.class.getPackage())
throw new IllegalAccessError(); // or similar
FYI `getClass()` gives you the class of `this`, which would the subclass's class.
Edited:
To find the caller's class, use this code:
Class<?> callerClass = Class.forName(Thread.currentThread().getStackTrace()[2].getClassName());
Problem
How can we restrict access of any protected method to only subclass in any package not to the class in the same package. If any class that is not the subclass and in same package also it must throw exception like "Protected method." Edit : Is there any way to check calling class name instance and then we can verify using instanceof .