What are the criteria for choosing between valueOf () and newInstance ()?

Suppose I have an ObjectInfo class that contains the name of the object and the type of the object as a String (I'm just preparing something to ask a question.)

class ObjectInfo {
    String objectName;

    String objectType;

    private ObjectInfo(String objectName, String objectType) {
          this.objectName = objectName;
          this.objectType = objectType;
    }
}

And if I want to provide a static factory method to instantiate this class, which of the following two methods is better and why?

public static ObjectInfo newInstance(String objectName, String objectType) {
    return new ObjectInfo(objectName, objectType)    
}

public static ObjectInfo valueOf(String objectName, String objectType) {
    return new ObjectInfo(objectName, objectType)    
}

Basically, I want to ask when should we use valueOf () and when is newInstance ()? Are there any conventions among the programming community?

-Ankit

+5
source share
4 answers
 public static ObjectInfo newObjectInfo(String objectName, String objectType)

For the static factory method, I would use the above naming convention. This is useful if the consumer of the method wants to use static imports:

import static foo.ObjectInfo.newObjectInfo;
//....
ObjectInfo info = newObjectInfo(foo, bar);

API Guava.

0

, ,

valueOf acquire , , .

newInstance create , .

get , , , null, .

newInstance create.

c.f.

Integer.valueOf(1) == Integer.valueOf(1) // you get the same object
Integer.valueOf(-200) != Integer.valueOf(-200) // you get a different object.
+3

, java, String.valueOf() , . (Integer, Double) OF() ( "12" ) .

, . factory. newInstance.

0

You answered your question when you said a And If I want to provide a static factory method to creating instances of this class new instance makes sense in this context (even if both valueOf and new do the same). To me, valueOf (as the name implies) makes sense when you want to get some meaningful state information from an existing object (not necessarily the entire state of the object), where it newcreates a new instance.

0
source

All Articles