dimanche 14 octobre 2018

Automatically call static block without explicitly calling Class.forName

Asume the following code:

public class Main {

    public static final List<Object> configuration = new ArrayList<>();

    public static void main(String[] args) {
        System.out.println(configuration);
    }
}

I now want to be able, to provide "self-configuring" classes. This means, they should be able to simply provide something like a static block, that will get called automatically like this:

public class Custom {
    static {
        Main.configuration.add(Custom.class);
    }
}

If you execute this code, the configuration list is empty (because of the way static blocks are executed). The class is "reachable", but not "loaded". You could add the following to the Main class before the System.out

Class.forName("Custom");

and the list would now contain the Custom class object (since the class is not initialized yet, this call initializes it). But because the control should be inverse (Custom should know Main and not the other way around), this is not a usable approach.

What would be possible though is the following: You could add an Annotation to the class and collect all classes with said annotation, using something like the ClassGraph framework and call Class.forName on each of them.

TL;DR

Is there a way, to automatically call the static block without the need to analyze all loaded classes? Perfect would be an approach, that, upon starting the application, automatically initializes a classes (if they are annotated with a certain annotation). I thought about custom ClassLoaders, but from what i understand, they are lazy and therefor not usable for this approach.

The background of this is, that i want to incorporate it into an annotation processor, which creates "self configuring code".





Aucun commentaire:

Enregistrer un commentaire