SIGN UP MEMBER LOGIN:    
ARTICLE

Accessing Private Fields and Private Methods (Hacking a Class) in Java

Posted by Abhishek Dubey Articles | Java February 02, 2012
This article is about the use of the reflection API. After reading this article you will be able to access private methods and private data like Password, User name etc so you can hack a class in Java.
Reader Level:

Accessing private Fields and private Methods (Hacking A Class) in Java

In Java by using the Reflection API, found in the java.lang.reflect package, you can access private fields and methods of another class. It is not even that difficult. This can be very handy during unit testing. If you try to access a field and a method of an applet then you will need to make a change in the SecurityManager setting. One Important thing is that this will work only when the code is running standalone as in a Java application.

Access  fields value of other class

There are two methods; first one is Class.getDeclareField(String obj) and the second is  Class.getDeclareFields( ) both the methods only return public fields so they would not work. So you use setAccessible() method which has a default value of false but you can set it to true.

Example

import java.lang.reflect.*;

// this is the class which contain private fields name as
public class PrivateObject
 
{
  private String privateString = null;
  public PrivateObject(String privateString)
      {
        this.privateString = privateString;
      }
  }
class PrivateTest
 
{
    public static void main(String arg[])
      {
        try{
 
        PrivateObject privateObject = new PrivateObject(" you Successfully  access the Private data Value of a class");
         // this is way to access the field of which class you want to access private data member.
         Field privateStringField = PrivateObject.class.getDeclaredField("privateString");
         // this setAccessible method has by default value false but you change it as true.
         privateStringField.setAccessible(true);
        // By using get method you access the field value and it type cast in String form.
        String fieldValue = (String) privateStringField.get(privateObject);
        System.out.println("fieldValue = " + fieldValue);
           }catch(Exception e)
              {
           System.out.println(e);
              }
     }
  }

OUTPUT

You can see that the private string is accessed by another class named PrivateTest.

privateobject.gif

Access  Method of other class

There are two methods; the first one is Class.getDeclareMethod(String obj, Class[] parameter types ) and the second is Class.getDeclareMethods( ); both the methods only return public Methods so they would not work. So you can use the setAccessible() method which has a default value of false but you set it to true.

Example

import java.lang.reflect.*;

// this is the class which contain private fields and method name as
public class PrivateObject1
 {
  private String privateString = null;
  public PrivateObject1(String privateString)
     {
     this.privateString = privateString;
     }
 //this is private method which return a string
  private String getPrivateString()
       {
        return this.privateString;
       }
 }

//this is another class which is used private method named as getPrivateString()
class PrivateMethodTest
 {
  public static void main(String arg[])
   {
    try{
 
        PrivateObject1 privateObject = new PrivateObject1("now you successful run the private method ");
        // this is way to access the field of which class you want to access private data member.
        Method privateStringMethod = PrivateObject1.class.getDeclaredMethod("getPrivateString", null);
       // this setAccessible method has by default value false but you change it as true.
       privateStringMethod.setAccessible(true);
      
// By using invoke method you run the private method and it value is type casting in String form.
       String returnValue = (String)privateStringMethod.invoke(privateObject, null);
      
//print the value which return after the excuting private method
       System.out.println("returnValue = " + returnValue);
      }catch(Exception e)
          {
          System.out.println(e);
          }
   }
 }

Note: a SecurityException is thrown by the methods getDeclaredField, getDeclaredMethod and setAccessible methods so you need to use Exception handling in this program; that is why we use a try and catch blocks; put these statements within this block.

OUTPUT

You can see that the private method is run in another class boundry named PrivateMethodTest But its a method of the PrivateObject1 class.

 privateobject1cmd.gif

Resources

How to Find All the Constructors, Fields and Methods of a Class in JAVA

What are Access Modifiers in C#?

How to use FileWriter and FileReaderClass in JAVA

Login to add your contents and source code to this article
share this article :
post comment
 
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor