184

私は列挙型を次のように宣言します:

enum Sex {MALE,FEMALE};

次に、以下に示すように列挙型を繰り返します。

for(Sex v : Sex.values()){
    System.out.println(" values :"+ v);
}

Java APIを確認しましたが、values()メソッドが見つかりませんか?この方法がどこから来ているのか知りたいですか?

APIリンク: https ://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html

4

3 に答える 3

192

このメソッドはコンパイラによって追加されているため、javadocには表示されません。

3つの場所で文書化:

コンパイラは、列挙型を作成するときに、いくつかの特別なメソッドを自動的に追加します。たとえば、列挙型のすべての値を宣言された順序で含む配列を返す静的値メソッドがあります。このメソッドは通常、for-each構文と組み合わせて使用​​され、列挙型の値を反復処理します。

  • Enum.valueOfクラス
    (特別な暗黙valuesのメソッドはメソッドの説明で言及されていますvalueOf

列挙型のすべての定数は、その型の暗黙的なpublic static T [] values()メソッドを呼び出すことで取得できます。

このvalues関数は、列挙のすべての値をリストするだけです。

于 2012-12-01T11:58:49.383 に答える
36

メソッドは暗黙的に定義されます(つまり、コンパイラーによって生成されます)。

JLSから:

さらに、Eが型の名前である場合enum、その型には次の暗黙的に宣言されたstaticメソッドがあります。

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);
于 2012-12-01T12:00:59.863 に答える
12

これを実行します

    for (Method m : sex.class.getDeclaredMethods()) {
        System.out.println(m);
    }

あなたが見るでしょう

public static test.Sex test.Sex.valueOf(java.lang.String)
public static test.Sex[] test.Sex.values()

これらはすべて、「sex」クラスが持つパブリックメソッドです。それらはソースコードに含まれていません、javac.exeはそれらを追加しました

ノート:

  1. クラス名としてsexを使用しないでください。コードを読み取るのは困難です。JavaではSexを使用します。

  2. このようなJavaパズルに直面するときは、バイトコード逆コンパイラツールを使用することをお勧めします(Andrey LoskutovのバイトコードアウトラインEclispeプラグインを使用します)。これにより、クラス内のすべてが表示されます

于 2012-12-01T17:28:34.183 に答える