Java泛型的泛型 [英] Java generics of generics of

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

问题描述

我有一个通用类,代表一段文本。文本片段可以具有多种不同模式(不同类型的突出显示)中的任何一种。这些模式由枚举代表。每个项目的枚举可能不同,但它必须实现一个接口,提供一种组合其中2个(可以突出显示和加粗)的方法。所以我有一个界面:

  public interface TextFragmentMode< E extends Enum&E; {
/ **
*将组合提供的模式与当前模式并返回
*结果。
*
* @param模式要结合的模式。
* @return组合模式。
* /
public E combine(E mode);
}

然后我的TextFragment是一个文本字符串和一个模式的容器。但是当我尝试声明类时:

  public class TextFragment< E extends TextFragmentMode& E extends Enum&E>>> ; {
StringBuilder text;
E模式;
...

我收到以下错误:


令牌上的语法错误extends,预期


eclipse语法突出显示,是指

  E扩展枚举& 

部分代码。有谁知道我做错了什么?我必须缺少关于泛型的东西...



--------------------- edit --- ----------------



我终于花时间阅读Josh Bloch的有效Java(第二版)事实证明,他将这个用例视为项目34:模拟具有接口的可扩展枚举。就像我想说的那样,很高兴认为,这样做会太过分了!

解决方案

TextFragment< E> 需要说两件关于 E




  • 它扩展 TextFragmentMode< E>

  • 为了做到这一点,你还必须约束它扩展枚举< E>



由于Java继承的勇气,你需要写另一种方式:

  public class TextFragment< E extends Enum< E> &安培; TextFragmentMode< E  - 代替;> {


I have a generic class which represents a fragment of text. That fragment of text may have any of a number of different modes (different types of highlighting). Those modes are represented by an Enum. The Enum could be different for each project but it must implement an interface which provides a method to combine 2 of them (could be highlighted and bolded). So i have an interface:

public interface TextFragmentMode<E extends Enum<E>> {
    /**
     * Will combine the supplied mode with the current mode and return the
     * result.
     * 
     * @param mode The mode to combine with.
     * @return The combined mode.
     */
    public E combine( E mode );
}

Then my TextFragment is a container for both a String of text, and a mode. But when I try to declare the class:

public class TextFragment<E extends TextFragmentMode<E extends Enum<E>>> {
    StringBuilder text;
    E mode;
    ...

I get the following error:

Syntax error on token "extends", , expected

Which, according to eclipse syntax highlighting, is referring to the

E extends Enum<E>

portion of the code. Does anyone know what I am doing wrong? I must be missing something about Generics...

--------------------- edit -------------------

I'm finally taking the time to read Effective Java by Josh Bloch (second edition), and it turns out he goes over this use case as Item 34: Emulate extensible enums with interfaces. As much as I would like to say great mind think alike... That would be WAY too presumtuous!

解决方案

TextFragment<E> needs to say two things about E.

  • It "extends" TextFragmentMode<E>.
  • In order to do that, you must also constrain it to extend Enum<E>.

Because of Java inheritance wonkiness, you need to write that the other way around:

public class TextFragment<E extends Enum<E> & TextFragmentMode<E>> {

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

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