How to call private method from another class in javaYou can call the private method from outside the class by changing the runtime behaviour of the class. With the help of java.lang.Class class and java.lang.reflect.Method class, we can call a private method from any other class. Required methods of Method class1) public void setAccessible(boolean status) throws SecurityException sets the accessibility of the method. 2) public Object invoke(Object method, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException is used to invoke the method. Required method of Class class1) public Method getDeclaredMethod(String name,Class[] parameterTypes)throws NoSuchMethodException,SecurityException: returns a Method object that reflects the specified declared method of the class or interface represented by this Class object. Example of calling private method from another classLet's see the simple example to call private method from another class. File: A.java File: MethodCall.java Output: hello java Another example to call parameterized private method from another classLet's see the example to call parameterized private method from another class File: A.java File: M.java Output: 64 Accessing Private Constructors of a classWe know that constructors of a class are a special kind of method this is used to instantiate the class. To access the private constructor, we use the method getDeclaredConstructor(). The getDeclaredConstructor() is used to access a parameterless as well as a parametrized constructor of a class. The following example shows the same. FileName: PvtConstructorDemo.java Output: Vehicle Id: 20 Vehicle Name: Indica -------------------------- Vehicle Id: 30 Vehicle Name: Alto Next TopicJava Date |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India