简体   繁体   中英

How to get an object using a string in Java

I've been trying to make my code more efficient, and I'm stuck on an issue where I have to repeat myself a lot to create 40+ objects (which results in 40+ functions with basically the same code, just different objects and different values). I am wondering if there is a way to make something like this in Java:

public void createObject(String objectName) {
    getObject(objectName).setType(ymlFile.getString(objectName + ".type")); 
    // getObject(objectName) would be the object which has the same name as the value of the string objectName
}

Currently I have to have basically this code (with more variables) for over 40 objects, so I was wondering if it is possible to be able to retrieve the object by using the value in the string called objectName, thus meaning that I only have to call the method 40 times, instead of having the big block of code 40 times.

Thanks.

EDIT: No, this isn't to do with YAML (not really anyway, just showing some of the code). My main issue is I need to be able to retrieve objects by using values of a string.

As for examples of the repetitive code, it's basically this:

    public void createObject1() {
        object1.setType(type1);
    }
    public void createObject2() {
        object2.setType(type2);
    }
    // etc. for about 40 objects. basically i want to be able to change that to this:
    public void createObject(String objectName) {
        objectName.setType("value"); // so basically, retrieve the object that has the same name as the value of objectName
    }

This looks like a case of the XY problem to me.

You probably just want to use two arrays to keep track of all objects and types, especially since it's really bad practice to name variables something1 , something2 and so on.

So replace your object and type variables with:

YourClass[] objects = new YourClass[40];
Type types = new Type[40];

and replace your creatObject() methdod with:

public void createObject(int index) {
    objects[index].setType(types[index]);
}

which you could even loop over like this:

// This condition is overkill since both arrays should have the same size,
// but if you plan on doing something different than that, this should work.
for(int i = 0; i < objects.length && i < types.length; i++)
    createObject(i);

If you really want to use strings though, you could do the same thing with a Map<String, YourClass> and a Map<String, Type> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM