接受两种类型的通用类 [英] Generic class that accepts either of two types

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

问题描述

  class MyGenericClass< T extends Number> 

我想创建一个这种形式的泛型类: {}

问题是,我希望T可以被接受为Integer或Long,但不能双。因此,只有两个可接受的声明是:

  MyGenericClass< Integer>实例; 
MyGenericClass< Long>实例;

有没有办法做到这一点?

解决方案

答案是否定的。至少没有办法使用泛型类型来完成它。我会推荐泛型和工厂方法的组合来做你想做的事。

  class MyGenericClass< T extends Number> {
public static MyGenericClass< Long> newInstance(Long value){
return new MyGenericClass< Long>(value);
}

public static MyGenericClass< Integer> newInstance(Integer value){
返回新的MyGenericClass< Integer>(value);
}

//隐藏构造函数,所以你必须使用工厂方法
private MyGenericClass(T value){
//实现构造函数
}
// ...实现类
public void frob(T number){
//用T
做一些事情}
}
MyGenericClass< Integer>
$ b>可以创建MyGenericClass< Long> 实例。尽管您仍然可以声明 MyGenericClass< Double> 类型的变量,它只需要为空。


I want to make a generic class of this form:

class MyGenericClass<T extends Number> {}

Problem is, I want to be acceptable for T to be either Integer or Long, but not Double. So the only two acceptable declarations will be:

MyGenericClass<Integer> instance;
MyGenericClass<Long> instance;

Is there any way to do that?

解决方案

The answer is no. At least there is no way to do it using generic types. I would recommend a combination of generics and factory methods to do what you want.

class MyGenericClass<T extends Number> {
  public static MyGenericClass<Long> newInstance(Long value) {
    return new MyGenericClass<Long>(value);
  }

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

  // hide constructor so you have to use factory methods
  private MyGenericClass(T value) {
    // implement the constructor
  }
  // ... implement the class
  public void frob(T number) {
    // do something with T
  }
}

This ensures that only MyGenericClass<Integer> and MyGenericClass<Long> instances can be created. Though you can still declare an variable of type MyGenericClass<Double> it will just have to be null.

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

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