Junior — Middle
Can a private class method be called from outside its definition?
sobes.tech AI
Answer from AI
In Java, you cannot directly call a class's private method from outside its definition because the private modifier restricts access to within the class itself.
However, using reflection, it is possible to access and invoke private methods despite these restrictions. For example:
import java.lang.reflect.Method;
class MyClass {
private void secret() {
System.out.println("Private method called");
}
}
public class Test {
public static void main(String[] args) throws Exception {
MyClass obj = new MyClass();
Method method = MyClass.class.getDeclaredMethod("secret");
method.setAccessible(true); // remove access restriction
method.invoke(obj); // call the private method
}
}
Thus, a normal call is impossible, but reflection allows bypassing this restriction.