1

I need to get static values from different class on the initialization of the application, I'm using @PostConstruct and I don't know how to retrieve all these values without creating an instance of each class

  • 1
    Show us what have you tried so far? – Coder Jul 16 '19 at 14:34
  • 1
    static members belong to the class instead of a specific instance, so I don't understand why do you need to create objects – Adrian Jul 16 '19 at 14:34
  • Because I need to do it dynamically, I can't ask for specific classes or attributes, I need a way to find all of this automatically, maybe with inheritance on the class with the static fields, but that's it. – Alan Vallvé Jul 17 '19 at 15:13

2 Answers2

4

You could user reflection (Class name can be even dynamically passed):

package com.example;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class Main {

    public static void main(String[] args)
            throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
        printStaticFieldsAndValues("com.example.ClassWithStaticFields");
    }

    private static void printStaticFieldsAndValues(String className)
            throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
        Class clazz = Class.forName(className);
        for (Field f : clazz.getDeclaredFields()) {
            if (Modifier.isStatic(f.getModifiers())) {
                System.out.println("Name: " + f.getName());
                System.out.println("Value " + f.get(null));
            }
        }
    }
}

Class which has static fields:

package com.example;

public class ClassWithStaticFields {

    static String stringField = "String Value";

}

Output:

Name: stringField
Value String Value
Guru
  • 964
  • 9
  • 12
  • This is really close, but there's a way to retrieve all the classes with the static fields automatically? Without the name of the class. – Alan Vallvé Jul 17 '19 at 15:15
  • Using reflection library, you should be able to get all classes based on package name - https://github.com/ronmamo/reflections. Please refer Addendum section of accepted answer of https://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection. Hope it helps. – Guru Jul 18 '19 at 08:22
0

Try static initializer on the class

public class OtherClass {

   public static final String VALUE = "SomeValue";

}

public class SomeClass {

   static {
      OtherClass.VALUE;
   }
}

And do whatever you want.

Emanuel Ramirez
  • 392
  • 2
  • 8
  • The problem is that I can't use the specific class which contains the static field, I have to find all these static fields, automatically – Alan Vallvé Jul 17 '19 at 15:14