Here i am calling private method method1() in PrivateMethodClass from another class CallingMethod. the below is the source code, which i tried.
Source Code:
PrivateMethodClass.java
package com.src;
public class PrivateMethodClass {
private void method1(int a,int b){
System.out.println("Var:a:"+a+"::Var b:"+b);
int c = a+b;
System.out.println("Var c:"+c);
}
public void method2(int a,int b){
System.out.println("Var:a:"+a+"::Var b:"+b);
int c = a+b;
System.out.println("Var c:"+c);
}
}
CallingMethod.java
package com.src;
import java.lang.reflect.Method;
public class CallingMethod {
public static void main(String[] args) {
Class klass;
try {
klass = PrivateMethodClass.class;
PrivateMethodClass pmc = new PrivateMethodClass();
Class[] param = {Integer.TYPE,Integer.TYPE};
Method m[] = klass.getDeclaredMethods();
int c =0;
int a[] = {1,2};
for(int i=0;i
m[i].setAccessible(true);
m[i].invoke(pmc,1,2);
}
} catch (Exception e) {
System.out.println("Exception::"+e.getMessage());
}
}
}
The Output Result:
Method name is method1
Var:a:1::Var b:2
Var c:3
Method name is method2
Var:a:1::Var b:2
Var c:3
Source: http://vishalnjain.blogspot.com/
No comments:
Post a Comment