2011-05-11 10 views
7

की इन्स्टेन्शियशन मजबूर करने के लिए मैं निम्नलिखित कोड के उत्पादन की काफी हैरान था:कैसे स्थिर क्षेत्रों

देश वर्ग

public class Country { 

    private static Map<String, Country> countries = new HashMap<String, Country>(); 

    private final String name; 

    @SuppressWarnings("LeakingThisInConstructor") 
    protected Country(String name) { 
     this.name = name; 
     register(this); 
    } 

    /** Get country by name */ 
    public static Country getCountry(String name) { 
     return countries.get(name); 
    } 

    /** Register country into map */ 
    public static void register(Country country) { 
     countries.put(country.name, country); 
    } 

    @Override 
    public String toString() { 
     return name; 
    } 

    /** Countries in Europe */ 
    public static class EuropeCountry extends Country { 

     public static final EuropeCountry SPAIN = new EuropeCountry("Spain"); 
     public static final EuropeCountry FRANCE = new EuropeCountry("France"); 

     protected EuropeCountry(String name) { 
      super(name); 
     } 
    } 

} 

मुख्य विधि

System.out.println(Country.getCountry("Spain")); 

आउटपुट

अशक्त

वहाँ वर्ग का विस्तार देश लोड करने के लिए इतना देशों मानचित्र सभी देश उदाहरण हों, के लिए मजबूर कर के किसी भी स्वच्छ रास्ता नहीं है?

उत्तर

7

हाँ, static initializer block का उपयोग करें:

public class Country { 

    private static Map<String, Country> countries = new HashMap<String, Country>(); 

    static { 
     countries.put("Spain", new EuroCountry("Spain")); 

    } 

... 
+0

+1। बस ध्यान दें कि स्थिर ब्लॉक या तो देश कोड में या कक्षा में मुख्य होना चाहिए। – Tarlog

+0

केवल समस्या यह है कि आप यूरोप कैंट्री खो देते हैं। स्पेन और यूरोपकंट्री। फ़्रांस संदर्भ। – eliocs

3

आपका वर्ग EuropeCountry बार जब आप Country.getCountry("Spain") कहा जाता है पर लोड नहीं हुई। सही समाधान

private static Map<String, Country> countries = new HashMap<String, Country>(); 

static { 
    // Do something to load the subclass 
    try { 
     Class.forName(EuropeCountry.class.getName()); 
    } catch (Exception ignore) {} 
} 

होगा यह एक उदाहरण मात्र है ... वहाँ (भी पीटर उत्तर देखें)

+0

मुझे इसे मजबूर करने का तरीका पसंद है। – eliocs

0

आप EuropeCountry वर्ग लोड करने के लिए की जरूरत है एक ही प्राप्त करने के लिए अन्य तरीके हैं। देश को कॉल करने से पहले इसका कोई भी संदर्भ पर्याप्त होगा।

संबंधित मुद्दे