我想创建类似integer或double的自定义类型。 免得说我有多级导航地图:// [UserLevel: [UserBalance: Multiplier]]
NavigableMap> multiplierByBalanceAndLevel
如果你不仔细看一下评论,这是绝对不可读的。 而且,当我使用这样的映射时,我总是应该转到声明并检查注释。 这真的很烦人,我想要这样的东西:NavigableMap> multiplierByBalanceAndLevel
例如,在scala中,可以使用:type UserLevel = Int
有没有可能以某种方式在Java实施? 也许有一些图书馆是为了这样的目的?
附注。 我可以用lombok帮助编写自定义实现import java.util.NavigableMap;
import com.google.common.collect.ImmutableSortedMap;
import lombok.Value;
import lombok.experimental.Delegate;
public class TestExample {
@Value
static class UserLevel extends Number implements Comparable {
@Delegate
Integer userLevel;
public int compareTo(UserLevel another) {
return this.userLevel.compareTo(another.getUserLevel());
}
}
@Value
static class UserBalance extends Number implements Comparable {
@Delegate
Double userBalance;
public int compareTo(UserBalance another) {
return this.userBalance.compareTo(another.getUserBalance());
}
}
@Value
static class Multiplier extends Number implements Comparable {
@Delegate
Double multiplier;
public int compareTo(Multiplier another) {
return this.multiplier.compareTo(another.getMultiplier());
}
}
public static void main(String[] args) {
double originalAmount = 10;
NavigableMap> multiplierByBalanceAndLevel =
ImmutableSortedMap.of(new UserLevel(1),
ImmutableSortedMap.of(new UserBalance(2.0), new Multiplier(3.0)));
Multiplier multiplier = multiplierByBalanceAndLevel
.floorEntry(new UserLevel(13)).getValue()
.ceilingEntry(new UserBalance(1.8)).getValue();
double amount = originalAmount * multiplier.getMultiplier();
}
}
但是使用包装好的类看起来很难看,而且会产生很多样板代码,因为它们的行为不像自动装箱的代码