Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private is Private, then Why java give facility to access private method using reflection? [duplicate]

What are the potential issues I need to look out for when using reflection. I am very confused in reflection, Why java provide this type of functionality to access private data member.

Private : Like I'd think, only the class in which it is declared can see it.

Then Why it is possible to access private things in other class? this terminology (reflection) completely overflow my concept of private(Access Specifier) properties in java.

I visited many links about this topics but not given complete explanation about this topics. eg:

package example;

import java.lang.reflect.Method;

class A{
    private void privateMethod(){
        System.out.println("hello privateMethod()");
    }
}
class B{
    public static void main(String[] args) throws Exception {
        A d = new A();
        Method m = A.class.getDeclaredMethod("privateMethod");       
        m.setAccessible(true);
        m.invoke(d);
    }
}

So please explain scenario about this approach in depth? I need advantage and disadvantage of private methods accessibility in other class?

like image 943
Avanish Singh Avatar asked Oct 16 '15 07:10

Avanish Singh


1 Answers

All "Private" and the other forms of declaration are, are flags for the development tool so that it knows how you intend to use the field or method in question. This is so the development tool can gives warnings or errors to the developer when they use these classes/fields/methods in a way they were not intended.

Reflection is a tool which lets the developer ignore or circumvent these flags which indicates that you are using the class/field/method in a way it was never intended. So in general reflection shows bad architecture.

So there are no "advantages or disadvantages" to declaring something as private or public or static; they're simply tools to help keep your code clean and compartmentalised by only allowing developers to access/use your classes/fields/methods in particular ways.

like image 55
Dynisious Avatar answered Sep 24 '22 11:09

Dynisious