vendredi 5 juin 2015

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?





Aucun commentaire:

Enregistrer un commentaire