Fortsätt till huvudinnehåll

Java Reflection, setting private fields that does not have a setter method

I was a bit puzzled when I was experimenting with GSON and noticed that it was possible to create new objects and set their private fields (member variables) even though there were no public setter methods for the private fields and there was no constructor that could be used to set them either.
When talking about it with a fellow developer he mentioned that probably Java Reflection was used.

Java Reflection can be used for a lot of things, see this comprehensive tutorial by Jakob Jenkov for a good overview. Below I will show how it can be used to set the private class members in the class below:

1:  public class Privates  
2:  {  
3:      private int privateInt;  
4:      private String privateString;  
5:      public int getPrivateInt()  
6:      {  
7:          return privateInt;  
8:      }  
9:      public String getPrivateString()  
10:      {  
11:          return privateString;  
12:      }  
13:  }  

An you can see there are no obvious ways how to set the members privateInt and privateString. However, it can be done using Reflection. Below is a unit test that shows how this can be done:

1:      @Test  
2:      public void testSetPrivateField()   
3:      {  
4:          Privates privatesObj = new Privates();  
5:          Field privateInt;  
6:          Field privateString;  
7:          try  
8:          {  
9:               privateInt = privatesObj.getClass().getDeclaredField("privateInt");  
10:              privateInt.setAccessible(true);  
11:              privateInt.set(privatesObj, 42);  
12:              privateInt.setAccessible(false);  
13:              privateString = privatesObj.getClass().getDeclaredField("privateString");  
14:              privateString.setAccessible(true);  
15:              privateString.set(privatesObj, "The answer to life the universe and everything");  
16:              privateString.setAccessible(false);  
17:          }  
18:          catch (NoSuchFieldException e)  
19:          {  
20:              assertTrue(false);  
21:          }  
22:          catch (IllegalAccessException e)  
23:          {  
24:              assertTrue(false);  
25:          }  
26:          assertEquals(42, privatesObj.getPrivateInt());  
27:          assertEquals("The answer to life the universe and everything", privatesObj.getPrivateString());  
28:      }  

Read the code above a couple of times to understand how it is done. The first step is to get the field using getDeclaredField, next the field is changed to accessible with the method setAccessible and finally the values are set using set.
Now, I do not recommend that you alter private members of a class, and I think it is strange that it can be done. But anyway, now you know that it can be done, and how.

Kommentarer

Populära inlägg i den här bloggen

C# Enum as bit field

Bit field enum Whenever you wish to express combinations of properties of an object, bit fields are a good way to accomplish this. As a simple example, consider a file in the file system. It can be Readable , Writable , Hidden or a combination these. The different attributes can be defined as an enum : [Flags] public enum FileAttribute {   None      = 0b0000;   Readable  = 0b0001;   Writeable = 0b0010;   Hidden    = 0b0100; } To indicate that this enum is expected to be used as a bit field I have defined it with the FlagsAttribute . It is important to understand that the FlagsAttribute does nothing more than making some changes to how the ToString method of the enum works, making it possible to print out all flags. It does not introduce any validation or special treatment of the enum in any other way. I have defined the values of the different fields of the enum using binary representation, this should make it even more clear that this is a bit field and which bi

Codility tasks - Part I

I was recently faced with two codility tasks when applying for a job as an Embedded Software Engineer. For those of you who arn't familiar with Codility you can check out their website here:  www.codility.com Task one - Dominator The first task was called Dominator. The goal was to, given a std::vector of integers, find an integer that occurs in more than half of the positions in the vector. If no dominator was found -1 should be returned. My approach was to loop through the vector from the first to the last element, using a std::map to count the number of occurences of each integer. If the count ever reached above half the size of the vector I stopped and returned that integer and if I reached the end without finding a dominator I returned -1. So was that a good approach? Well, the reviewer at the company rated the solution as 'pretty ok'. His preferred solution was store the first integer in the array and set a counter to 1. Then loop through the remaining i