2012-01-31 1 views

答えて

3

ジェネリック型にバインドする必要があります。

import java.util.*; 
public class GenericTest<C extends GenericTest.HasLongProperty> { 
    static interface HasLongProperty { 
     long someLongProperty(); 
    } 
    public long convertToLong(Collection<C> es) { 
     long a = 0; 
     for(C sth : es) 
      a += sth.someLongProperty(); 
     return a; 
    } 
} 

またはconvertToLongが含まれているクラスがジェネリックではない場合、あなたはその1つのメソッドの宣言でバウンドを置くことができます:convertToLongが含まれているクラスが同じ型でパラメータ化されている場合は、そこにバインドを置くことができます単独:

import java.util.*; 
public class GenericTest { 
    static interface HasLongProperty { 
     long someLongProperty(); 
    } 
    public <C extends GenericTest.HasLongProperty> long convertToLong(Collection<C> es) { 
     long a = 0; 
     for(C sth : es) 
      a += sth.someLongProperty(); 
     return a; 
    } 
} 
+0

これは有効な構文ではありません – newacct

+0

@newacct、ありがとうこれを指摘している。構文を修正し、必要な汎用バインドを宣言する2つの異なる方法を示す追加のサンプルを追加しました。 –

2

私はあなたがこのような何かをしたいと思う:

public <T extends SomeType> long convertToLong(Collection<T> es) { 

    long a = 0; 

    for(T sth : es) { 
     a += sth.someLongProperty(); 

    } 
    return a; 
    } 

これはTがSomeTypeとSomeTypeのいずれかのサブクラスが機能someLongPropertyを持っていることができるタイプTのセットに渡すことができると述べています。

+0

なぜ、それは任意のコレクションの代わりに 'セット'ですか?この手法を適用するには、要素を区別する必要がありますか? – Borealid

+0

これは 'public long convertToLong(Collection <?extends SomeType> es){'および 'for'行を' for(SomeType sth:es){'に簡略化することができます – newacct

2

このコードでは、次のコードを実行します。重要なのはタイプを複数のタイプ(この場合Enum )にバインドする汎用構文を使用することです。

これは、コンパイルされます。

public interface HasSomeLongProperty { 
    long someLongProperty(); 
} 

public static enum Fruit implements HasSomeLongProperty { 
    apple(1), 
    orange() { 
     // You may override the default implementation and delegate 
     public long someLongProperty() { 
      // You could also make this a field and not new every call 
      new SomeHasSomeLongPropertyImpl().someLongProperty(); 
     } 
    }; 

    private long value; 

    private Fruit() { 
    } 

    private Fruit(long value) { 
     this.value = value; 
    } 

    public long someLongProperty() { 
     return value; 
    } 
} 

public static <T extends Enum<T> & HasSomeLongProperty> long convertToLong(EnumSet<T> es) { 
    long a = 0; 
    for (T sth : es) 
     a += sth.someLongProperty(); 
    return a; 
} 
+0

convertToLongは何とかHasSomeLongProperty(スーパークラス)の一部になる可能性があるので、必要に応じて列挙型のバリエーションをオーバーライドできますか? – Blankman

+0

残念ながら、列挙型は何も拡張できません。単に実装することしかできません。いくつかの制限を除いて、列挙型は他のクラスと同じですので、他のクラスに委譲できます(http://en.wikipedia.org/wiki/Delegation_pattern)。匿名のスタイルを使用することもできます。example.commentsの編集済みの回答は5分間のみ編集可能です(このボックスをクリックすると解消されます) – Bohemian

0

うん - Javaの交差点の種類(ボヘミアンの答えは)あなたがやりたいです。私はgetDescription()メソッドを持っていたいと思ういくつかのenumクラスを持っていたのと同じ問題がありました。

一般に、交差の型は、列挙型をサブクラス化できないという問題を回避します。

関連する問題