Reputation: 1371
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?
UPD:
There is a solution that first instantiates all variables and then sequentally sets id
field. I'm still looking for the way to do it "atomically" in constructor.
Upvotes: 0
Views: 250
Reputation: 812
It's relatively easy to do so, the problem is knowing which field to use. You can mark it with an annotation which would make it easier. Something like
public String getFieldName(){
Field[] fields = getClass().getDeclaredFields();
for(Field f: fields){
if(f.isAnnotationPresent(YourAnnotation.class)){
return f.getName();
}
}
// do whatever if a valid field wasn't found
}
If you don't want an annotation then you'll have to find some other way to identify it, such as the only static field. But that's very bad practice and using an annotation is better.
Upvotes: 1