Last active
June 4, 2024 06:02
-
-
Save realfirst/8bb4719507253b65511a59bee8f39c40 to your computer and use it in GitHub Desktop.
java playground
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.*; | |
class MyClass { | |
private String privateField = "privateValue"; | |
public MyClass() {} | |
public MyClass(String arg) { | |
this.privateField = arg; | |
} | |
private void privateMethod(String arg) { | |
System.out.println("Private Method called with arg: " + arg); | |
} | |
public String getPrivateField() { | |
return privateField; | |
} | |
} |
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.*; | |
public class ReflectionExample { | |
public static void main(String[] args) throws Exception { | |
Class<?> clazz = MyClass.class; | |
// Access private field | |
Field field = clazz.getDeclaredField("privateField"); | |
field.setAccessible(true); | |
MyClass obj = new MyClass(); | |
System.out.println("Initial Field Value: " + field.get(obj)); | |
field.set(obj, "newPrivateValue"); | |
System.out.println("Updated Field Value: " + field.get(obj)); | |
// Access private method | |
Method method = clazz.getDeclaredMethod("privateMethod", String.class); | |
method.setAccessible(true); | |
method.invoke(obj, "testArg"); | |
// Access private contructor | |
Constructor<?> constructor = clazz.getDeclaredConstructor(String.class); | |
constructor.setAccessible(true); | |
MyClass newObj = (MyClass) constructor.newInstance("newInstanceArg"); | |
System.out.println("New Object Field Value: " + newObj.getPrivateField()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment