Having this method:
readAllTypes(Class clazz) {...}
Can I access the static variables of the class?
static variables are otherwise called as class variables, because they are available to each object of that class. As member is an object of the class Static, so you can access all static as wll as non static variables of Static class through member object.
The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.
A static member variable: • Belongs to the whole class, and there is only one of it, regardless of the number of objects. Must be defined and initialized outside of any function, like a global variable. It can be accessed by any member function of the class. Normally, it is accessed with the class scope operator.
Static Methods can access class variables(static variables) without using object(instance) of the class, however non-static methods and non-static variables can only be accessed using objects.
Yes. Just use Class.getDeclaredFields()
(or Class.getDeclaredField(String)
) as normal, and to get the values, use the Field.getXyz()
methods, passing in null
for the obj
parameter.
Sample code:
import java.lang.reflect.Field;
class Foo {
public static int bar;
}
class Test {
public static void main(String[] args)
throws IllegalAccessException, NoSuchFieldException {
Field field = Foo.class.getDeclaredField("bar");
System.out.println(field.getInt(null)); // 0
Foo.bar = 10;
System.out.println(field.getInt(null)); // 10
}
}
You can find the field using clazz.getDeclaredFields()
, which returns a Field[]
, or by directly getting the field by name, with clazz.getDeclaredField("myFieldName")
. This may throw a NoSuchFieldException
.
Once you've done that, you can get the value of the field with field.get(null)
if the field represents an object, or with field.getInt(null)
, field.getDouble(null)
, etc. if it's a primitive. To check the type of the field, use the getType
or getGenericType
. These may throw an IllegalAccessException
if they're not public, in which case you can use field.setAccessible(true)
first. You can also set the fields in the same way if you just replace "get" with "set".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With