mardi 18 juin 2019

Get static instance name in Java via reflection during construction

I am not sure if this is the right way to reduce number of characters written, but still.

Right now I have the following piece of code that maps to two settings sources: database and .properties file:

import lombok.*;

@Getter
@ToString
@EqualsAndHashCode
public final class Setting<T> {
    private String id;
    private Class<T> clazz;  

    private Setting(final String id, final Class<T> clazz) {
        this.id = id;
        this.clazz = clazz;
    }

    public static final Setting TOKEN_LENGTH = new Setting("TOKEN_LENGTH", Integer.class);
    // lots of other settings
}

The thing is, I want to avoid explicit passing of the first argument to the constructor, e.g. like variable named TOKEN_LENGTH has id TOKEN_LENGTH passed to it. In other way, when these static final variables are instantiated, their first argument is always the name of the said variable.

In this case there are only ~60 instances of this class are created and this happens only at application startup, so any overhead caused by reflection is acceptable.

I wonder if there any way to rewrite the constructor to look something like

    private Setting(final Class<T> clazz) {
        this.id = /* some crazy reflection magic */
        this.clazz = clazz;
    }

So, the question is:

➥ By chance, is there any way to get name of static variable for which the object is being instantiated and assigned to?





Aucun commentaire:

Enregistrer un commentaire