Last active
November 9, 2017 16:56
-
-
Save captswag/a9b2b7979f04e41d90174d457671ecaf to your computer and use it in GitHub Desktop.
Reflection in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.Method; | |
import java.lang.reflect.Field; | |
import java.lang.reflect.Modifier; | |
import java.lang.reflect.Constructor; | |
class ReflectionExample { | |
public static void main(String args[]) throws Exception { | |
// Examining & constructing object for Test class at runtime | |
Class<?> clazz = Class.forName("Test"); | |
Test test = (Test) clazz.newInstance(); | |
// Examininig and changing accessibilty of Test class's fields NUM_1 and assigning value at runtime | |
System.out.println("Making field NUM_1 accessible and assigning value 100"); | |
Field num1Field = test.getClass().getDeclaredField("NUM_1"); | |
num1Field.setAccessible(true); | |
num1Field.set(test, 100); | |
// Examining and changing accessibility of Test class's fields NUM_2 and assigning value at runtime | |
System.out.println("Making field NUM_2 accessible and assigning value 200"); | |
Field num2Field = test.getClass().getDeclaredField("NUM_2"); | |
num2Field.setAccessible(true); | |
num2Field.set(test, 200); | |
// Changing accessibilty & invoking sum() of test object at runtime | |
System.out.println("Making method sum() acccessible and invoking it"); | |
Method sumMethod = test.getClass().getDeclaredMethod("sum", int.class, int.class); | |
sumMethod.setAccessible(true); | |
int sum = (Integer) sumMethod.invoke(test, num1Field.get(test), num2Field.get(test)); | |
// Changing accessibilty & invoking printMessage() of test object at runtime | |
System.out.println("Making method printMessage() acccessible and invoking it"); | |
Method printMessageMethod = test.getClass().getDeclaredMethod("printMessage", int.class); | |
printMessageMethod.setAccessible(true); | |
printMessageMethod.invoke(test, sum); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Test { | |
private final int NUM_1 = 10; | |
private final int NUM_2 = 20; | |
private void printMessage(int sum) { | |
System.out.println(String.format("Sum is %d", sum)); | |
} | |
private int sum(int num1, int num2) { | |
return num1 + num2; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment