How to access private variables of Java Class – Hacking by reflection

1 Mins read

This example demonstrates how you can do object hacking in Java using the Reflection API. Hacking by reflection is possible through setAccessible() method provided in Reflection API. Most of the Java object hacking techniques utilize this to Hack objects.

In a typical Java application you will not be able to access a private variable of a class outside the class. If you use Reflection then you can access all private fields of a Java class. Here I am taking an example of password field.

SecureData class contains a private password field which does not provide any access to outside world. Code in main method of SecuredDataHack class demonstrates how we can easily access what is inside the password field. You can clearly see that its not only reading the fields but also setting it to new value, which could be disastrous.

package hacking;
import java.lang.reflect.Field;
public class SecuredDataHack {
public static void main(String[] args) throws Exception {
SecureData s = SecureData.class.newInstance();   
Field f[] = s.getClass().getDeclaredFields();   
Object pass = new Object();   
pass = f[0].get(s);   
System.out.println("Here is your " + f[0].getName() + " : " + pass );   
f[0].set(s, "NewPassword");   
pass = f[0].get(s);   
System.out.println("Here is new " + f[0].getName() + " : " + pass );

This is my class which contains a private attribute called password. I don’t want to allow anyone to have access of it so I did not provide any get or set method for it. Lets see if Reflection can Hack it?

package hacking;
public class SecureData {   
private String password = "MySecretPassword";

Below is the output of this program

Here is your password : MySecretPassword
Here is new password : NewPassword
Related posts

How to Access Kickass Torrents With Proxies

3 Mins read
Kickass Torrents was a popular website used by gamers, bookworms, music lovers, and movie and TV series fans worldwide. The site was…

3 Tips to Troubleshoot Readiness Probe Failed Errors Effectively : Kubernetes

4 Mins read
A Kubernetes readiness probe can improve your service’s quality and reduce operational issues, making your service more resilient and robust. However, the…

Is It good to Wear Eyeglasses for Software Engineers?

2 Mins read
As technology continues to be a fundamental tool in our day-to-day lives, we spend more time staring at digital screens. This may…
Power your team with InHype

Add some text to explain benefits of subscripton on your services.


Leave a Reply

Your email address will not be published. Required fields are marked *