Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access the static variables of the 'Class' Object?

Tags:

java

class

Having this method:

readAllTypes(Class clazz) {...}

Can I access the static variables of the class?

like image 766
SG Tech Edge Avatar asked Jul 09 '20 18:07

SG Tech Edge


People also ask

Can I access static variable using object?

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.

Can static member accessed through the class 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.

How do you access static class variables?

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.

Can instance of a class access static variables?

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.


Video Answer


2 Answers

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
    }
}
like image 148
Jon Skeet Avatar answered Oct 19 '22 04:10

Jon Skeet


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".

like image 22
user Avatar answered Oct 19 '22 03:10

user