TomTom
TomTom

Reputation: 33

Get instanced object by attribute

Is it possible to refer to an instanced object by it's value in Java?

    Object one = new Object("A");
    Object two = new Object("B");

    method(Object.getByValue("A"));

Depending on the situation I'd like to pick a different object. Obviously all the objects have to have a different value, otherwise there is no way to tell which one.

Upvotes: 1

Views: 49

Answers (2)

mostruash
mostruash

Reputation: 4189

It is possible.

class MyObject {
    private static Map<String, MyObject> map = new HashMap<>();

    public static MyObject createObject(String str) {
        MyObject newObj = new MyObject(str);
        map.put(str, newObj);
    }

    public static MyObject getObject(String str) {
        return map.get(str);
    } 

    private String name;

    public MyObject(String str) {
        this.name = str;
    }
}

Upvotes: 0

nanofarad
nanofarad

Reputation: 41281

I'm assuming you mean your own class. There's no Object(String) constructor.

Yes, but not directly. You'll need to create a map. In this case, we'll use HashMap. In MyObject, declare

static HashMap<String, MyObject> objects = new HashMap<>();

The constructor of MyObject will need to get a line added. Modify it to look like:

public MyObject(String stringParam);
    // existing constructor logic

    objects.put(stringParam, this); 
}

assuming stringParam is the constructor parameter you used.

You can then write a static method:

static MyObject getByValue(String s){ return objects.get(s); }

Upvotes: 1

Related Questions