Java annotation value use enum name

1. Background

  • Java annotation value must be constant
  • But some case want to use enum name(eg. spring-cache use enum config cache, operate cache need cache name)

2. Plan

Plan 1: name property + external name interface

1
2
3
4
5
6
7
8
9
@lombok.Getter
@lombok.AllArgsConstructor
public enum CommonCacheConfig {
    QUOTE_LEVEL(CommonCacheConstant.QUOTE_LEVEL, 2);

    private final String name;

    private final int ttl;
}
1
2
3
4
5
public interface CommonCacheConstant {

    String QUOTE_LEVEL = "QUOTE_LEVEL";

}

Usage:@Cacheable(cacheNames = CommonCacheConstant.QUOTE_LEVEL)

Plan 2: name property + internal name interface

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public enum CommonCacheConfig {
    QUOTE_LEVEL(Constant.QUOTE_LEVEL, 2);

    private final String name;
    private final Integer ttl;

    public interface Constant {
        String QUOTE_LEVEL = "QUOTE_LEVEL";
    }
}

Usage:@Cacheable(cacheNames = CommonCacheConfig.Constant.QUOTE_LEVEL)

Plan 3:Lombok’s FieldNameConstants

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@lombok.Getter
@lombok.AllArgsConstructor
@lombok.experimental.FieldNameConstants(onlyExplicitlyIncluded = true)
public enum CommonCacheConfig {

	@FieldNameConstants.Include QUOTE_LEVEL(2);

	private final Integer ttl;

}

Usage:@Cacheable(cacheNames = CommonCacheConfig.Fields.QUOTE_LEVEL)
Attention: FieldNameConstants’s onlyExplicitlyIncluded must set to true,otherwise generate by property(eg. ttl), and add @FieldNameConstants.Include before enum item.

3. Summary

The post first published at https://www.890808.xyz/ ,others update slowly.

javalover123