开发者

How to throw an exception when a main class tries to invoke a private method of another class?

开发者 https://www.devze.com 2023-01-21 09:42 出处:网络
Let\'s say I have a Cl开发者_如何学编程assA 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.

Let's say I have a Cl开发者_如何学编程assA 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消