繁体   English   中英

类似于 Java 中的盒装原语的自定义类型

[英]Custom type that acts like boxed primitive in Java

我想创建类似于IntegerDouble的自定义类型。 以免说我有多级可导航 map:

// [UserLevel: [UserBalance: Multiplier]]
NavigableMap<Integer, NavigableMap<Double, Double>> multiplierByBalanceAndLevel

如果您不查看评论,它绝对不可读。 而且当我使用这样的Map时,我也应该 go 到声明和检查评论。 这绝对很烦人,我想要类似的东西:

NavigableMap<UserLevel, NavigableMap<UserBalance, Multiplier>> multiplierByBalanceAndLevel

例如在 scala 中可以使用:

type UserLevel = Int

是否有可能以某种方式在 java 中实现? 也许有一些用于此类目的的库?

PS我可以用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<UserLevel> {
        @Delegate
        Integer userLevel;

        public int compareTo(UserLevel another) {
            return this.userLevel.compareTo(another.getUserLevel());
        }
    }

    @Value
    static class UserBalance extends Number implements Comparable<UserBalance> {
        @Delegate
        Double userBalance;

        public int compareTo(UserBalance another) {
            return this.userBalance.compareTo(another.getUserBalance());
        }
    }

    @Value
    static class Multiplier extends Number implements Comparable<Multiplier> {
        @Delegate
        Double multiplier;

        public int compareTo(Multiplier another) {
            return this.multiplier.compareTo(another.getMultiplier());
        }
    }

    public static void main(String[] args) {
        double originalAmount = 10;
        NavigableMap<UserLevel, NavigableMap<UserBalance, Multiplier>> 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();
    }
}

但是包装类的使用看起来很丑陋并且产生了很多样板代码,因为它们不像自动装箱的那样

Java 不支持自定义类的自动装箱或自动拆箱。


Java 中的装箱和拆箱转换分别在JLS 5.1.7JLS 5.1.8中指定。 他们 state 仅在原始类型和相应的包装类型之间进行转换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM