Java ResourceBundle getObject() 方法



描述

Java ResourceBundle getObject(String key) 方法從該資源包或其父級資源包中獲取給定鍵的物件。此方法首先嚐試使用 handleGetObject 從該資源包中獲取物件。如果未成功,並且父資源包不為空,則呼叫父資源包的 getObject 方法。如果仍然不成功,則丟擲 MissingResourceException 異常。

宣告

以下是 java.util.ResourceBundle.getObject() 方法的宣告

public final Object getObject(String key)

引數

key − 所需物件的鍵

返回值

此方法返回給定鍵的物件

異常

  • NullPointerException − 如果 key 為 null

  • MissingResourceException − 如果找不到給定鍵的物件

從美國區域設定的屬性檔案中獲取鍵對應的物件值

以下示例演示瞭如何使用 Java ResourceBundle getObject() 方法根據鍵獲取物件。我們為相應的 hello_en_US.properties 檔案建立了一個美國區域設定的資源包。然後,我們使用 getObject() 檢索分配給鍵 hello 的文字並將其打印出來。

package com.tutorialspoint;

import java.util.Locale;
import java.util.ResourceBundle;

public class ResourceBundleDemo {
   public static void main(String[] args) {

      // create a new ResourceBundle with specified locale
      ResourceBundle bundle = ResourceBundle.getBundle("hello", Locale.US);

      // print the text assigned to key "hello"
      System.out.println(bundle.getObject("hello"));
   }
}

輸出

假設在你的 CLASSPATH 中有一個名為 hello_en_US.properties 的資原始檔,其內容如下。此檔案將用作示例程式的輸入:

hello = Hello World!

讓我們編譯並執行上述程式,這將產生以下結果:

Hello World!

從法國區域設定的屬性檔案中獲取鍵對應的物件值

以下示例演示瞭如何使用 Java ResourceBundle getObject() 方法根據鍵獲取物件。我們為相應的 hello_fr_FR.properties 檔案建立了一個法國區域設定的資源包。然後,我們使用 getObject() 檢索分配給鍵 hello 的文字並將其打印出來。

package com.tutorialspoint;

import java.util.Locale;
import java.util.ResourceBundle;

public class ResourceBundleDemo {
   public static void main(String[] args) {

      // create a new ResourceBundle with specified locale
      ResourceBundle bundle = ResourceBundle.getBundle("hello", Locale.FRANCE);

      // print the text assigned to key "hello"
      System.out.println(bundle.getObject("hello"));
   }
}

輸出

假設在你的 CLASSPATH 中有一個名為 hello_fr_FR.properties 的資原始檔,其內容如下。此檔案將用作示例程式的輸入:

hello = Bonjour le monde!

讓我們編譯並執行上述程式,這將產生以下結果:

Bonjour le monde!

從德國區域設定的屬性檔案中獲取鍵對應的物件值

以下示例演示瞭如何使用 Java ResourceBundle getObject() 方法根據鍵獲取物件。我們為相應的 hello_de_DE.properties 檔案建立了一個德國區域設定的資源包。然後,我們使用 getObject() 檢索分配給鍵 hello 的文字並將其打印出來。

package com.tutorialspoint;

import java.util.Locale;
import java.util.ResourceBundle;

public class ResourceBundleDemo {
   public static void main(String[] args) {

      // create a new ResourceBundle with specified locale
      ResourceBundle bundle = ResourceBundle.getBundle("hello", Locale.GERMANY);

      // print the text assigned to key "hello"
      System.out.println(bundle.getObject("hello"));
   }
}

輸出

假設在你的 CLASSPATH 中有一個名為 hello_de_DE.properties 的資原始檔,其內容如下。此檔案將用作示例程式的輸入:

hello = Hallo Welt!

讓我們編譯並執行上述程式,這將產生以下結果:

Hallo Welt!
java_util_resourcebundle.htm
廣告

© . All rights reserved.