Find a private field with Reflection?
Use BindingFlags.NonPublic
and BindingFlags.Instance
flags
FieldInfo[] fields = myType.GetFields(
BindingFlags.NonPublic |
BindingFlags.Instance);
How to read the value of a private field from a different class in Java?
In order to access private fields, you need to get them from the class's declared fields and then make them accessible:
Field f = obj.getClass().getDeclaredField("stuffIWant"); //NoSuchFieldException
f.setAccessible(true);
Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException
EDIT: as has been commented by aperkins, both accessing the field, setting it as accessible and retrieving the value can throw Exception
s, although the only checked exceptions you need to be mindful of are commented above.
The NoSuchFieldException
would be thrown if you asked for a field by a name which did not correspond to a declared field.
obj.getClass().getDeclaredField("misspelled"); //will throw NoSuchFieldException
The IllegalAccessException
would be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out the f.setAccessible(true)
line.
The RuntimeException
s which may be thrown are either SecurityException
s (if the JVM's SecurityManager
will not allow you to change a field's accessibility), or IllegalArgumentException
s, if you try and access the field on an object not of the field's class's type:
f.get("BOB"); //will throw IllegalArgumentException, as String is of the wrong type
How to get the value of private field using reflection?
As others have said, since the field is private you should not be trying to get it with normal code.
The only time this is acceptable is during unit testing, and even then you need a good reason to do it (such as setting a private variable to null so that code in an exception block will be hit and can be tested).
You could use something like the method below to get the field:
/// <summary>
/// Uses reflection to get the field value from an object.
/// </summary>
///
/// <param name="type">The instance type.</param>
/// <param name="instance">The instance object.</param>
/// <param name="fieldName">The field's name which is to be fetched.</param>
///
/// <returns>The field value from the object.</returns>
internal static object GetInstanceField(Type type, object instance, string fieldName)
{
BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Static;
FieldInfo field = type.GetField(fieldName, bindFlags);
return field.GetValue(instance);
}
So you could call this like:
string str = GetInstanceField(typeof(YourClass), instance, "someString") as string;
Again, this should not be used in most cases.
Get a private field via reflection, in Java
Change this line
name = (String) myStringField.get(obj.getClass());
to this
name = (String) myStringField.get(obj);
The get method requires an object to access the field of (unless it's a static field)
Use reflection to find a private field within `this` class, and instantiate it
Activator.CreateInstance(Type)
can create an instance from the type. This requires a parameter-less constructor (there are overloads for parameters).
To use it, just modify your code a little bit:
public class TestClass
{
private SomeClass sc;
private AnotherClass ac;
public TestClass()
{
var type = GetType();
type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.ToList()
.ForEach(f => {
f.SetValue(this, Activator.CreateInstance(f.FieldType);
});
}
}
Set private field value with reflection
To access a private field you need to set Field::setAccessible
to true. You can pull the field off the super class. This code works:
Class<?> clazz = Child.class;
Object cc = clazz.newInstance();
Field f1 = cc.getClass().getSuperclass().getDeclaredField("a_field");
f1.setAccessible(true);
f1.set(cc, "reflecting on life");
String str1 = (String) f1.get(cc);
System.out.println("field: " + str1);
Get all private fields using reflection
It is possible to obtain all fields with the method getDeclaredFields()
of Class
. Then you have to check the modifier of each fields to find the private ones:
List<Field> privateFields = new ArrayList<>();
Field[] allFields = SomeClass.class.getDeclaredFields();
for (Field field : allFields) {
if (Modifier.isPrivate(field.getModifiers())) {
privateFields.add(field);
}
}
Note that getDeclaredFields()
will not return inherited fields.
Eventually, you get the type of the fields with the method Field.getType().
How to access a private field of the super class of the super class with reflection in Java?
The fact that you need to do this points to a flawed design.
However, it can be done as follows:
class A
{
private int privateField = 3;
}
class B extends A
{}
class C extends B
{
void m() throws NoSuchFieldException, IllegalAccessException
{
Field f = getClass().getSuperclass().getSuperclass().getDeclaredField("privateField");
f.setAccessible(true); // enables access to private variables
System.out.println(f.get(this));
}
}
Call with:
new C().m();
One way to do the 'walking up the class hierarchy' that Andrzej Doyle was talking about is as follows:
Class c = getClass();
Field f = null;
while (f == null && c != null) // stop when we got field or reached top of class hierarchy
{
try
{
f = c.getDeclaredField("privateField");
}
catch (NoSuchFieldException e)
{
// only get super-class when we couldn't find field
c = c.getSuperclass();
}
}
if (f == null) // walked to the top of class hierarchy without finding field
{
System.out.println("No such field found!");
}
else
{
f.setAccessible(true);
System.out.println(f.get(this));
}
Related Topics
Difference Between Asynchronous Programming and Multithreading
How to Get the Color from a Hexadecimal Color Code Using .Net
Setting the Default Json Serializer in ASP.NET MVC
Reading CSV File and Storing Values into an Array
How to Get the Ip Address of the Server on Which My C# Application Is Running On
Set Focus on Textbox in Wpf from View Model
Get List of Connected Usb Devices
How to Convert Numbers Between Hexadecimal and Decimal
How to Convert Image to Byte Array
When to Use .First and When to Use .Firstordefault With Linq
How to Get the Current Username in .Net Using C#
Why Do I Get "'Property Cannot Be Assigned" When Sending an Smtp Email
C# Convert Int to String With Padding Zeros
How to Convert a C# String Value to an Escaped String Literal