Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java prevent calling private or protected methods outside of class

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?

like image 473
Lajos Arpad Avatar asked Jun 05 '15 14:06

Lajos Arpad


People also ask

Can we call protected method from outside class Java?

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.

Can private methods be called outside the class?

You can only use private methods with: This means you can't call private methods from outside the class that defines them.

How can we prevent other classes from accessing a method?

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

Can subclass call protected method?

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.


1 Answers

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.

like image 62
Phil Anderson Avatar answered Sep 30 '22 16:09

Phil Anderson