限制泛型类型 [英] Limiting generic type

查看:114
本文介绍了限制泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中是否可以将泛型类型< T> 限制为仅限某些类型:

Is it possible in Java to limit a generic type <T> to only some types like:


  • 布尔值

  • 整数


  • Float

  • 字符串

  • Boolean
  • Integer
  • Long
  • Float
  • String

编辑:我的问题是将通用类型< T> 限制为不同的类型没有共同的直接超类。

Edit: My problem is to limit a generic type <T> to different class types which have not common direct superclass.

编辑:我最终使用了Reimeus提出的方案:

Edit: I finally use the scheme proposed by Reimeus:

public class Data<T> {

    private T value;

    private Data(T value) {
        this.set(value);
    }

    public static Data<Integer> newInstance(Integer value) {
        return new Data<Integer>(value);
    }

    public static Data<Float> newInstance(Float value) {
        return new Data<Float>(value);
    }

    public static Data<String> newInstance(String value) {
        return new Data<String>(value);
    }

    public T get() {
        return this.value;
    }

    public void set(T value) {
        this.value = value;
    }
}

和:

Data<Integer> data = Data.newInstance(10);






编辑:另一个方法:

public class Data<T> {

    private T value;

    private Data(T value) {
        this.set(value);
    }

    @SuppressWarnings("unchecked")
    public Data(Integer value) {
        this((T) value);
    }

    @SuppressWarnings("unchecked")
    public Data(Float value) {
        this((T) value);
    }

    @SuppressWarnings("unchecked")
    public Data(String value) {
        this((T) value);
    }

    public T get() {
        return this.value;
    }

    public void set(T value) {
        this.value = value;
    }
}

但我遇到问题:

如果错误地将 data 实例声明为:

If by mistake the data instance is declared with:

Data<Integer> data = new Data<Integer>(3.6f); // Float instead of Integer

没有类强制转换异常和数据。 get()返回 3.6

There is no class cast exception and data.get() returns 3.6

我不明白为什么...

I don't understand why...

所以,第一个解决方案似乎更好。

推荐答案

使用单个声明类型< T> 是不可能的,但您可以定义一个包装类,为所需类型提供工厂方法

Not possible using a single declared type <T> but you could define a wrapper class that provides factory methods for the required type

public class Restricted<T> {

    private T value;

    public Restricted(T value) {
        this.value = value;
    }

    public static Restricted<Boolean> getBoolean(Boolean value) {
        return new Restricted<Boolean>(value);
    }

    public static Restricted<Integer> getInteger(Integer value) {
        return new Restricted<Integer>(value);
    }

    public static Restricted<Double> getLong(Double value) {
        return new Restricted<Double>(value);
    }

    // remaining methods omitted
}

这篇关于限制泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆