views:

582

answers:

4

Is it possible in Java to access private field str via reflection? For example to get value of this field.

class Test
{
   private String str;
   public void setStr(String value)
   {
      str = value;
   }
}
+17  A: 

Yes, it absolutely is - assuming you've got the appropriate security permissions. Use Field.setAccessible(true) first if you're accessing it from a different class.

import java.lang.reflect.*;

class Other
{
    private String str;
    public void setStr(String value)
    {
        str = value;
    }
}

class Test
{
    public static void main(String[] args)
        // Just for the ease of a throwaway test. Don't
        // do this normally!
        throws Exception
    {
        Other t = new Other();
        t.setStr("hi");
        Field field = Other.class.getDeclaredField("str");
        field.setAccessible(true);
        Object value = field.get(t);
        System.out.println(value);
    }
}

And no, you shouldn't normally do this...

Jon Skeet
There are very few instances where you should do this, as Jon noted. I have unfortunately had to do it more than I care to admit, and it makes for VERY ugly code.
aperkins
FAIL. If you remove the call to `setAccessible` it still works, even with a security manager present. :) But +1 for "you shouldn't normally do this".
Tom Hawtin - tackline
@Tom: Thanks, fixed up the example to a situation where you *do* need to do it :)
Jon Skeet
Nice correction. (See Guideline 6-4 of Secure Coding Guidelines Version 2.0 for the Java Programming Language: http://java.sun.com/security/seccodeguide.html )
Tom Hawtin - tackline
@Downvoter: Care to explain why?
Jon Skeet
+8  A: 

Yes.

  Field f = Test.class.getDeclaredField("str");
  f.setAccessible(true);//Very important, this allows the setting to work.
  String value = (String) f.get(object);

then you use the field object to get the value on an instance of the class.

Note that get method is often confusion for people. You have the field, but you don't have an instance of the object. You have to pass that to the get method

Yishai
Short. Succinct. Thumbs up.
Christian
+1  A: 

Yes it is possible.

You need to use the getDeclaredField method (instead of the getField method), with the name of your private field:

Field privateField = Test.class.getDeclaredField("str");

Additionally, you need to set this Field to be accessible, if you want to access a private field:

privateField.setAccessible(true);

Once that's done, you can use the get method on the Field instance, to access the value of the str field.

pythonquick
+1  A: 

Yes, it is possible.

duffymo