1

Java クラスのヘルパーとして Enum を使用している場合、その Enum をクラス外で参照する方法はありますか?

基本的に、私が持っているのはこれです:

class Account extends MyClass {
    HashMap<Property, String> property = new HashMap<Property, String>();
    public Account() {
    }

    public enum Property {
        USERID,
        PASSWORD;
    }
}

Account クラスの外部の Property 列挙型にアクセスできるようにしたいと考えています。これを行う理由は、これが別のサブクラスであり、一意の列挙名を参照せずに特定のサブクラスのプロパティにアクセスできるようにしたいからです (つまり、それぞれを参照せずに、たとえば、 AccountProperty または ResearchProperty または TaskProperty... など)。

4

3 に答える 3

3

列挙型は公開されているため、クラスAccount.Property外からアクセスするために使用できますAccount

編集 :

必要なものを手に入れたら、次のようなことをしたい

Property p = Account.Property.PASSWORD;
Property p1 = Product.Property.CODE;

製品がどこにあるか

public class Product extends MyClass{
    HashMap<Account.Property, String> property = new HashMap<>();
    public Product() {
    }

    public static enum Property {
        CODE,
        PRICE;
    }
}

でこれを行いたいとしますMyClass

問題は、2 つの行の両方でインポートが必要であり、同じ名前の 2 つのクラスをインポートできないため、唯一の解決策は次のようにすることです。

Account.Property p = Account.Property.PASSWORD;
Product.Property p1 = Product.Property.CODE;

列挙型を拡張する方法がないため、各クラスに適切な列挙型instanceofを使用するには、に対処する必要があると思います!Property

于 2012-05-19T16:17:19.720 に答える
1

おそらく次のようなものです(ただし、これには型チェックがありません):

import java.util.*;
abstract class MyClass {
    Map<Object,String> properties=new HashMap<Object,String>();
}
class Account extends MyClass {
    enum Property {
        userid,password
    }
    //static Set<Property> keys=EnumSet.allOf(Property.class);
}
class Research extends MyClass {
    enum Property {
        red,green;
    }
    static Set<Property> keys=EnumSet.allOf(Property.class);
}
public class So10666881 {
    public static void main(String[] args) {
        Account account=new Account();
        account.properties.put(Account.Property.userid,"user");
        account.properties.put(Account.Property.password,"pass");
        for(Account.Property property:Account.Property.values())
            System.out.println(property+"="+account.properties.get(property));
    }
}
于 2012-05-19T17:18:25.350 に答える
0

列挙型をパブリックトップレベルの列挙型クラスとして宣言するだけです(独自のファイルで)

于 2012-05-19T16:16:32.047 に答える