top of page
Writer's pictureSagar Patel

can we invoke private method from outside of a class in Java

yes we can call private method outside of class by help of reflection. there are some steps that we have to follow


1) create demo class with private method

2 ) create another class test

3) inside test class get Class class instance for demo class

4) get object of demo class by help of newInstance() method of Class class

5) get method and set Accessible true

6) invoke method


public Demo { step 1


private void message(){


System.out.println("yes we can call private method outside of class ");


}

}





package com.Reflection.API;


import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;


public class Test{ step 2


public static void main(String[] args) {


try {


Class c = Class.forName("com.Reflection.API.Demo"); step 3


Demo o = (Demo) c.newInstance(); step 4


Method m = c.getDeclaredMethod("message", null); step 5


m.setAccessible(true); step 5


m.invoke(o, null); step 6


} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException

| SecurityException | IllegalArgumentException | InvocationTargetException e) {

e.printStackTrace();

}


}


}



output yes we can call private method outside of class


16 views0 comments

Recent Posts

See All

Battle of the Backends: Java vs Node.js

Comparing Java and Node.js involves contrasting two distinct platforms commonly used in backend development. Here’s a breakdown of their...

Comments


bottom of page