I know that we can access private constructor via reflection as @Sanjay T. Sharma mentioned in his answer of my question: Does “instanceof Void” always return false?
you can access private everything with reflection – methods, constructors, data members, everything.
- How can I access the private methods and the private data members?
- Is it possible to access local variable via reflection?
- Is there a way to prevent anyone from accessing private constructors, methods, and data members?
1) How can I access the private methods and the private data members?
You can do it with a little help of the
setAccessible(true)method:2) Is it possible to access a local variable via reflection?
No. Local variables cannot be accessed outside of a block in which they were created (someone could say that you can assign such a variable to a field like
field = localVariable;and later access such a field via reflection, but this way we will be accessing the value, not the variable).3) Is there any way to prevent anyone from accessing private constructors, methods, and data members?
I think for
constructorsormethodsyou could use stacktrace to check if it was invoked byReflection.For fields I can’t find a solution to prevent accessing them via reflection.
[WARNING: This is not approved by anyone. I just wrote it inspired by your question.]
Output from
Testmain method: