![]() Refer following example to use Class.getDeclaredField(String name) for accessing field if you know name and signature of method. This class also provides two methods Class.getField(String name, Class parameterTypes) and Class.getFieldss() but these methods can be use to invoke public fields only as first one will return only matched public field and second will return all public fields. To access private fields Java reflection class Class provides two methods Class.getDeclaredField(String name) and Class.getDeclaredFields() by using anyone of these two you can invoke private fields(s). String res =(String)privateMethod.invoke(privateObject, null) PrivateMethod.invoke(privateObject, "My Name is Anupama From private method param") PrivateMethod = ("printName", new Class) Assign all parameter type in Class Array PrivateMethod.invoke(privateObject,null) Method privateMethod = ("printName", null) MYClass privateObject = new MYClass("My Name is Anupama") While Class.getDeclaredMethods() is used to list all declared methods in class and by using some logic you can invoke particular method. Refer following example to use Class.getDeclaredMethod(String name, Class parameterTypes) for invoking method if you know name and signature of method. This class also provides two methods Class.getMethod(String name, Class parameterTypes) and Class.getMethods() but these methods can be use to invoke public methods only as first one will return only matched public method and second will return all public methods. To access private method Java reflection class Class provides two methods Class.getDeclaredMethod(String name, Class parameterTypes) and Class.getDeclaredMethods() by using anyone of these two you can invoke private method(s). ![]() Here is sample private class with one private field and three methods(return value, with parameter, without parameter) to explain how you can actually do this.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |