Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does setProperty in Java return Object?

Tags:

java

The Properies class in Java SE 6 has a method called setProperty(String key, String value), which returns an Object. Furthermore, the previous Object stored for this key, or NULL if none exists. Since setProperty(String key, String value) can only take a String as value, why doesn't that method return a String?

like image 946
MechMK1 Avatar asked May 20 '12 17:05

MechMK1


People also ask

What does system setProperty do in Java?

The System. setProperty() method forms the basis for test case automation on any browser. Naturally, QAs must understand how to use this fundamental method for all automation purposes in Selenium.

Is setProperty thread safe?

SO is System. setProperty safe ? No. Do not use this.

How do you read the properties of an object in Java?

Properties is a subclass of Hashtable. It is used to maintain a list of values in which the key is a string and the value is also a string i.e; it can be used to store and retrieve string type data from the properties file. Properties class can specify other properties list as it's the default.

What Does properties mean in Java?

Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String. The Properties class is used by many other Java classes. For example, it is the type of object returned by System. getProperties( ) when obtaining environmental values.


2 Answers

Unfortunately class java.util.Properties was introduced into java 1.0, many years before generics. Properties extends Hashtable that can store any type of data. So, you can do the following:

Properties props = new Properties();
props.put("key", new Object());  // use Hashtable's put method
props.setProperty("key", "value"); // use Proerties' setProperty method

In this example setProperty must return the previous value stored in this entry, i.e. Object. But it is not String! To avoid ClassCastException the JDK creators had to define setProperty() as method that returns Object.

BTW even now class Properties implements Map<Object, Object> instead of Map<String, String> for backwards compatibility.

like image 144
AlexR Avatar answered Oct 19 '22 19:10

AlexR


Because Properties was misconceived from the start by extending Hashtable, which can store anything. The design thus didn't respect the Liskov substitution principle: everything a base class can do, a subclass must be able to do.

Since Properties extends Hashtable, you can in fact store any kind of Object in it.

like image 13
JB Nizet Avatar answered Oct 19 '22 19:10

JB Nizet