-4

Say I am getting names of people and want to create person objects of the same name, something like this :

void foo(String str){
       Person str = new Person();
}

So that later I can refer to the person by name, something like :

int getAcoountNumber(String str){
      return str.acNumber;
}
  • 1
    Look into Java reflection API – Juned Ahsan Dec 16 '14 at 04:21
  • 4
    It's extremely unclear what you actually want, but I'd wager reflection isn't it. From the example you've given, I'd suggest looking into `java.util.Map`, and googling around much more. – Chris Hayes Dec 16 '14 at 04:24
  • You can have a node, which have that pass string and value stored. later you can identify that node using string. – Sarz Dec 16 '14 at 04:25
  • It can be done by reflection but same kind of feature be achieved by using Map. – Panther Dec 16 '14 at 04:27
  • 2
    I agree with Chris Hayes. Given the information provided, it seems you should be using a data structure to load Persons into memory and call upon them by some ID. So, make a Person class with an ID property, and load them into a HashMap data structure, and find your 'People' by looking up their String IDs in the map. – ThisClark Dec 16 '14 at 04:31

1 Answers1

3

I think you need a map for String str to Person str.

say the map is HashMap nameMap, and change the code like this:

void foo(String str){
    Person p = new Person(str);
    nameMap.put(str, p);
}

int getAcoountNumber(String str){
      return nameMap.get(str).acNumber;
}
vmcloud
  • 650
  • 4
  • 13
  • 1
    Probably correct, but since users have a tendency to misspell things, you probably want to check `nameMap.get(str)` for `null` before trying to access any of its members. – ajb Dec 16 '14 at 04:46