There, i am going to write the code in two ways :
1. By using Object's class getClass() method.
package reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class A {
private void test() {
System.out.println("from test");
}
private static void testStatic() {
System.out.println("from static test");
}
}
public class MainAccess {
public static void main(String args[]) {
A obj = new A();
Class c = obj.getClass(); //getClass() method is from Object class
try {
Method m = c.getDeclaredMethod("test"); // from reflection
m.setAccessible(true);
Object o = m.invoke(obj, new Object[]{}); // from reflection
Method mStatic = c.getDeclaredMethod("testStatic");
mStatic.setAccessible(true);
Object oStatic = mStatic.invoke(A.class, new Object[]{});
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
}
}
}
package reflection;Download Source Code
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {
private void test() {
System.out.println("from test");
}
public static void main(String[] args) {
// TODO code application logic here
try {
Class c = Class.forName("reflection.Main");
Method m = c.getDeclaredMethod("test");
Object o = c.newInstance();
m.invoke(o);
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
}
}
}
Click here to download complete source code
0 comments:
Post a Comment