Is this possible to do? I am looking to parse some data out of a file and based on the results of this take names found in the file and create objects out of them. for example...

//you have parsed the name Bob out of a file and it is stored in an array of Strings at location 1. 
public static String[] parsedPlayers = {"Bill", "Bob", "Joe", "Jane", "Jill"};

//Now what i want to do is use the names above as variable names and pass them as arguments to the constructor, but i dont know how to create a variable out of them.

Player XXXXXX = new Player(XXXXXX);

//constructor

public Player(String name) {
        playerName = name;
        immunities = immunityNames;
    }

Anyone know how i would go about doing this?

My teacher mentioned something about introspection when i asked him, but my research has been futile and i have not seen any methods that would help me with this.

TJ

Recommended Answers

All 4 Replies

There isn't a mechanism to do that easily, but you really shouldn't have any need to. Just set a "name" property on the Player object. A HashMap can provide easy indexing of them if you need it for look up purposes.

hmm okay, i'll look into hashmaps. but the other reason i wanted to do that is because i can retroactively add objects in a method when a new name is come across, but now i have to provide for the highest possible number of people dont I?

TJ

No, you can store the player objects in a dynamic collection, like an ArrayList or the HashMap that I mentioned above. You don't have to have a unique variable name for every object in your code - that is what arrays and collections are for.

When your teacher said "introspection " the Java word is "Reflection", which you can Google if you want.
Having said that, you do NOT want to use Reflection for this. What Ezzaral says is exactly right - use a HashMap<String><Player>

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.