Let's supppose that I have created a Java library, called Foo
and I have a class inside that library called Bar
. Let's suppose further that in the Bar
class I have a private method, called fooBar
.
public class Bar {
//...
private Object fooBar() {
//Do something
}
//...
}
One can run this method without any difficulties with a code written in a class, like this:
public static Object runMethod(Object object, String methodName) {
Method method = object.getClass().getDeclaredMethod(methodName);
method.setAccessible(true);
return method.invoke(object);
}
However, let us suppose that we intend to discourage this habit for fooBar
. How can we do something like that? Should we get the stack trace from somewhere and check where it was called? Or should we do something else?
The protected access modifier is accessible within the package. However, it can also accessible outside the package but through inheritance only. We can't assign protected to outer class and interface. If you make any constructor protected, you cannot create the instance of that class from outside the package.
You can only use private methods with: This means you can't call private methods from outside the class that defines them.
When you declare a method in a Java class, you can allow or disallow other classes and object to call that method. You do this through the use of access specifiers. The Java language supports five distinct access levels for methods: private, private protected, protected, public, and, if left unspecified, "friendly".
protected means access to the method is restricted to the same package or by inheritance. So the answer is, yes, protected methods can be overridden by a subclass in any package.
You need a security manager...
https://docs.oracle.com/javase/tutorial/essential/environment/security.html
A security manager is an object that defines a security policy for an application. This policy specifies actions that are unsafe or sensitive. Any actions not allowed by the security policy cause a SecurityException to be thrown. An application can also query its security manager to discover which actions are allowed.
It supports disallowing setAccessible()
to make private and protected methods invocable via reflection.
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