Java正式类型参数定义(泛型) [英] Java formal type parameter definition (Generics)

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

问题描述

我想定义一个泛型类型,它的实际类型参数只能是


  1. 其中一个数字原始包装类 Long 整数浮点 Double

  2. 字符串

我可以用这样的定义来满足第一个要求

  public final class MyClass< T extends数> {
//执行省略
}

但我无法弄清楚如何满足他们两个。我怀疑这实际上是不可能的,因为AFAIK在定义正式类型参数时没有办法指定或语义,尽管你可以使用诸如

的定义来指定和语义

  public final class MyClass< T extends Runnable&可串行化> {
//执行省略
}

干杯,
Don

解决方案

Java泛型不支持联合类型(此参数可以是A或B)。

在一些可能对某些人感兴趣的相关说明中,如果您想强制执行多个限制,则它支持多个边界。以下是Java 泛型教程中提到的JDK示例:

  public static< T extends Object&可比< ;? super T>> T max(Collection<?extends T> coll)


I'd like to define a generic type, whose actual type parameter can only be

  1. One of the numeric primitive wrapper classes (Long, Integer, Float, Double)
  2. String

I can meet the first requirement with a definition like this

public final class MyClass<T extends Number> {
    // Implementation omitted
}

But I can't figure out how to meet both of them. I suspect this is not actually possible, because AFAIK there's no way to specify "or" semantics when defining a formal type parameter, though you can specify "and" semantics using a definition such as

public final class MyClass<T extends Runnable & Serializable > {
    // Implementation omitted
}

Cheers, Don

解决方案

Java generics does not support union types (this parameter can be A OR B).

On a related note that may be of interest to some, it does support multiple bounds, if you want to enforce multiple restrictions. Here's an example from the JDK mentioned in the Java generics tutorial:

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)

这篇关于Java正式类型参数定义(泛型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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