Java Utility Library

Java ResourceBundle - getObject() Method



The java.util.ResourceBundle.getObject() method is used to get an object for the given key from this resource bundle or one of its parents. This method first tries to obtain the object from this resource bundle using handleGetObject. If not successful, and the parent resource bundle is not null, it calls the parent's getObject method. If still not successful, it throws a MissingResourceException.

Syntax

public final Object getObject(String key)

Parameters

key Specify the key for the desired object.

Return Value

Returns the object for the given key.

Exception

  • Throws NullPointerException, if key is null.
  • Throws MissingResourceException, if no object for the given key can be found.

Example:

Lets assume that we have resource file called Greetings_en_US.properties in the CLASSPATH with the following content. This file contains local message for US country.

greet = Hello World!

In the below Java program, the java.util.ResourceBundle.getObject() method is used to get the object for the given key from the above mentioned resource bundle Greetings_en_US.properties.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a resource bundle in specified locale
    ResourceBundle bundle = ResourceBundle.getBundle("Greetings", Locale.US);

    //printing the text object assigned to  
    //"greet" key in the bundle
    System.out.println(bundle.getObject("greet"));   
  }
}

The output of the above code will be:

Hello World!

❮ Java.util - ResourceBundle