java – How to throw an exception when a main class tries to invoke a private method of another class? – Education Career Blog

Let’s say I have a ClassA class and a methodA private method in Java.

In my ClassB class I have a main method where I invoke MethodA. This should not work, obviously.

What can I do to throw an Exception or Error when this happens during the runtime.

Thanks.

,

The only possible way I know to call private methods of one class from another not inner class is with the help of reflection.

You can get all methods, set some private methods accessible and invoke them. To prevent this you just need to set a SecurityManager in the main method (google for further investigation).

If you just want to make the part of compilers work by yourself, then there’s no such necessity. Just use any mature IDE and it will outline for you the potential compile-time error as soon as you do it.

Leave a Comment