Читаем Программирование на Java полностью

public class MyResource extends ResourceBundle { private Hashtable res = null; public MyResource() { res = new Hashtable(); res.put("TestKey","English Variant"); } public Enumeration getKeys() { return res.keys(); } protected Object handleGetObject(String key) throws java.util.MissingResourceException { return res.get(key); } } public class MyResource_ru_RU extends ResourceBundle { private Hashtable res = null; public MyResource_ru_RU() { res = new Hashtable(); res.put("TestKey","Русский вариант"); } public Enumeration getKeys() { return res.keys(); } protected Object handleGetObject(String key) throws java.util.MissingResourceException { return res.get(key); } } public class Test { public Test() { } public static void main(String[] args) { Test test = new Test(); ResourceBundle rb = ResourceBundle.getBundle("experiment.MyResource",Locale.getDefault()); System.out.println(rb.getString("TestKey")); rb = ResourceBundle.getBundle("experiment.MyResource", new Locale("ru","RU")); System.out.println(rb.getString("TestKey")); } } Пример 14.29.

Результатом будет:


English Variant Русский Вариант

Кроме того, следует обратить внимание, что ResourceBundle может хранить не только строковые значения. В нем можно хранить также двоичные данные, или просто методы, реализующие нужную функциональность, в зависимости от локали.


public interface Behavior { public String getBehavior(); public String getCapital(); } public class EnglishBehavior implements Behavior{ public EnglishBehavior() { } public String getBehavior(){ return "English behavior"; } public String getCapital(){ return "London"; } } public class RussianBehavior implements Behavior { public RussianBehavior() { } public String getBehavior(){ return "Русский вариант поведения"; } public String getCapital(){ return "Москва"; } } public class MyResourceBundle_ru_RU extends ResourceBundle { Hashtable bundle = null; public MyResourceBundle_ru_RU() { bundle = new Hashtable(); bundle.put("Bundle description","Набор ресурсов для русской локали"); bundle.put("Behavior",new RussianBehavior()); } public Enumeration getKeys() { return bundle.keys(); } protected Object handleGetObject(String key) throws java.util.MissingResourceException { return bundle.get(key); } } public class MyResourceBundle_en_EN extends ResourceBundle { Hashtable bundle = null; public MyResourceBundle_en_EN() { bundle = new Hashtable(); bundle.put("Bundle description","English resource set"); bundle.put("Behavior",new EnglishBehavior()); } public Enumeration getKeys() { return bundle.keys(); } protected Object handleGetObject(String key) throws java.util.MissingResourceException { return bundle.get(key); } } public class MyResourceBundle extends ResourceBundle { Hashtable bundle = null; public MyResourceBundle() { bundle = new Hashtable(); bundle.put("Bundle description","Default resource bundle"); bundle.put("Behavior",new EnglishBehavior()); } public Enumeration getKeys() { return bundle.keys(); } protected Object handleGetObject(String key) throws java.util.MissingResourceException { return bundle.get(key); } } public class Using { public Using() { } public static void main(String[] args) { Using u = new Using(); ResourceBundle rb = ResourceBundle.getBundle("lecture.MyResourceBundle", Locale.getDefault()); System.out.println((String)rb.getObject("Bundle description")); Behavior be = (Behavior)rb.getObject("Behavior"); System.out.println(be.getBehavior()); System.out.println(be.getCapital()); rb = ResourceBundle.getBundle("lecture.MyResourceBundle", new Locale("en","EN")); System.out.println((String)rb.getObject("Bundle description")); Behavior be = (Behavior)rb.getObject("Behavior"); System.out.println(be.getBehavior()); System.out.println(be.getCapital()); } Пример 14.30.

Результатом будет:


Русский набор ресурсов Русский вариант поведения Москва English resource bundle English behavior London Пример 14.31.

Классы ListResourceBundle и PropertiesResourceBundle

У класса ResourceBundle определено два прямых потомка ListResourceBundle и PropertiesResourceBundle. PropertiesResourceBundle хранит набор ресурсов в файле, который представляет собой набор строк.


Перейти на страницу:

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных
1001 совет по обустройству компьютера
1001 совет по обустройству компьютера

В книге собраны и обобщены советы по решению различных проблем, которые рано или поздно возникают при эксплуатации как экономичных нетбуков, так и современных настольных моделей. Все приведенные рецепты опробованы на практике и разбиты по темам: аппаратные средства персональных компьютеров, компьютерные сети и подключение к Интернету, установка, настройка и ремонт ОС Windows, работа в Интернете, защита от вирусов. Рассмотрены не только готовые решения внезапно возникающих проблем, но и ответы на многие вопросы, которые возникают еще до покупки компьютера. Приведен необходимый минимум технических сведений, позволяющий принять осознанное решение.Компакт-диск прилагается только к печатному изданию книги.

Юрий Всеволодович Ревич

Программирование, программы, базы данных / Интернет / Компьютерное «железо» / ОС и Сети / Программное обеспечение / Книги по IT