Get Value of a Public Static Field via Reflection

Get value of a public static field via reflection

You need to pass null to GetValue, since this field doesn't belong to any instance:

fields[0].GetValue(null)

How to get the value of a private static field from a class?

Yes.

Type type = typeof(TheClass);
FieldInfo info = type.GetField(name, BindingFlags.NonPublic | BindingFlags.Static);
object value = info.GetValue(null);

This is for a field. For a property, change type.GetField to type.GetProperty. You can also access private methods in a similar fashion.

Get parent's static field value via reflection

the type indicated by derivedType has no field field. This is statically bound to the Base-class. So you have two opportunities

  1. use the base-type:

    Type derivedType = // retrieve a type derived from Base
    FieldInfo fieldInfo = derivedType.BaseType.GetField("field", BindingFlags.Static | BindingFlags.Public); // is nul
  2. flatten the hierarchy to get all fields from base-classes also:

    Type derivedType = // retrieve a type derived from Base
    FieldInfo fieldInfo = derivedType.GetField("field", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);

Apart from this there´s no need to use reflection in your case, you don´t need an instance to access a static field. That´s the entire use of static. Just use this:

ISomeInterface a = Base.field;

Getting value of public static final field/property of a class in Java via reflection

First retrieve the field property of the class, then you can retrieve the value. If you know the type you can use one of the get methods with null (for static fields only, in fact with a static field the argument passed to the get method is ignored entirely). Otherwise you can use getType and write an appropriate switch as below:

Field f = R.class.getField("_1st");
Class<?> t = f.getType();
if(t == int.class){
System.out.println(f.getInt(null));
}else if(t == double.class){
System.out.println(f.getDouble(null));
}...

Get value of static field

You can use the following:

var field = typeof(Pages).GetField("Home", BindingFlags.Public | BindingFlags.Static);
var value = (string)field.GetValue(null);

C# - Faster way to get set public static fields instead of using Reflection.SetValue / GetValue

You can use expressions for this. You basically have three options:

  1. Reflection. Slow.
  2. Dynamic compiled expression. Fast.
  3. Typed compiled expression. Super fast.

In your case it's a bit tricky to go for typed expressions. I guess we cannot assume that all static properties will be of type string? The second option allows you to easily create a fast setter for any field type.

Note that when compiling expressions, you must maintain a cache for the compiled delegates. The compilation step is very expensive!

class Program
{
public class Foo
{
public static string Name;
}

public static void Main()
{
var delegateCache = new Dictionary<(string, string), Delegate>();

var typeName = typeof(Foo).FullName;
var fieldName = "Name";

var key = (typeName, fieldName);

// Caching is crucial!
if (!delegateCache.TryGetValue(key, out var d))
{
d = CreateStaticSetter(typeName, fieldName);
delegateCache.Add(key, d);
}

// For a strongly typed delegate, we would use Invoke() instead.
d.DynamicInvoke("new value");

Console.WriteLine(Foo.Name);
}

private static Delegate CreateStaticSetter(string typeName, string fieldName)
{
var type = Type.GetType(typeName) ?? throw new ArgumentException();
var field = type.GetField(fieldName) ?? throw new ArgumentException();

var valueExp = Expression.Parameter(field.FieldType, "value");
var fieldExp = Expression.Field(null, field);
var assignExp = Expression.Assign(fieldExp, valueExp);

// TODO: Can be further optimized with a strongly typed delegate.
var expr = Expression.Lambda(assignExp, valueExp);
return expr.Compile();
}
}

Get value of static field from Class

Try with reflection

Steps to follow:

  • First retrieve the declared field of the class using its variable name
  • Check the type of the returned field
  • Then call corresponding method on Field to get the field value

Sample code:

ArrayList<Class<? extends A>> list = new ArrayList<Class<? extends A>>();
list.add(B.class);
list.add(A.class);

// get the value of first class stored in array
Field f = list.get(0).getDeclaredField("i");
Class<?> t = f.getType();
if (t == int.class) {
System.out.println(f.getInt(null));
}

EDIT

As per @Sotirios Delimanolis comments you can get the value directly without checking field type and mathodField#getX() as shown below but it will return Object instead of primitive int.

Field f = list.get(0).getDeclaredField("i");
System.out.println(f.get(null));

Get value of static field using reflection in kotlin for generic type

I found the solution. I forgot to set isAccessible to true. It doesn't matter if the static field is marked as public, isAccessible still has to be set to true for some reason.

Get field values using reflection

Something like this...

import java.lang.reflect.Field;

public class Test {
public static void main(String... args) {
try {
Foobar foobar = new Foobar("Peter");
System.out.println("Name: " + foobar.getName());
Class<?> clazz = Class.forName("com.csa.mdm.Foobar");
System.out.println("Class: " + clazz);
Field field = clazz.getDeclaredField("name");
field.setAccessible(true);
String value = (String) field.get(foobar);
System.out.println("Value: " + value);
} catch (Exception e) {
e.printStackTrace();
}
}
}

class Foobar {
private final String name;

public Foobar(String name) {
this.name = name;
}

public String getName() {
return this.name;
}
}

Or, you can use the newInstance method of class to get an instance of your object at runtime. You'll still need to set that instance variable first though, otherwise it won't have any value.

E.g.

Class<?> clazz = Class.forName("com.something.Foobar");
Object object = clazz.newInstance();

Or, where it has two parameters in its constructor, String and int for example...

Class<?> clazz = Class.forName("com.something.Foobar");
Constructor<?> constructor = clazz.getConstructor(String.class, int.class);
Object obj = constructor.newInstance("Meaning Of Life", 42);

Or you can interrogate it for its constructors at runtime using clazz.getConstructors()

NB I deliberately omitted the casting of the object created here to the kind expected, as that would defeat the point of the reflection, as you'd already be aware of the class if you do that, which would negate the need for reflection in the first place.



Related Topics



Leave a reply



Submit