top of page

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


 
 
 

Recent Posts

See All

Comments


MiIT Logo

Company

Contact Us

+1905-487-4880 

5160 Explorer Dr #34, Mississauga,ON L4W 4T7

+1929-743-3199

4466 Buttonwood Ln Lilburn, GA 30047

262 Chapman Rd, STE 240 Newark DE 19702

+44 20 4525 1214

71-75 Shelton Street, Covent Garden, London, United Kingdom WC2H 9JQ

Stay up to date on the latest from MiIT

  • Instagram
  • Facebook
  • http://linkedin.com/company/miittechnologies/about/
  • Whatsapp

© All Content MiIT Technologies Inc.2019 - 2025. All rights reserved.

bottom of page