0

I want the user to enter the name of the object to be used in the code. For example, if I have a class

public class Person{ 
.......
}

now instead of me creating an object with a specific name like

Person student;

I want the user to enter the name for the object maybe like teacher, and then an object teacher of the class person will be created. I do not know if this is even possible in java, many of the solutions I looked up were using a map, but the explanations were not clear enough for me as I am new to java.

So, if anyone could explain how it can be done with code snippets it would be wonderful.

Also please explain how hashmaps work in java and if they can be used to implement the problem above. I would be really grateful if explained with code examples

Deanna
  • 23,876
  • 7
  • 71
  • 156
CurryMaster
  • 151
  • 1
  • 2
  • 5
  • 1
    First in Java class are used to start with upper case letter. Secondly why are you trying to do that ? – BaptisteL Apr 06 '14 at 11:11
  • There are many ways to achieve what you ask for, although it really depends on your use of those objects. You could use a map which maps key to a value, in this case you could use Map. But maybe it would be better to have a field in your class: `private String name;`. Also note that there's no way to access variable name at runtime, so your example is not a very good one. – Kuba Spatny Apr 06 '14 at 11:12
  • man this is a bad design and i wont agree on this method of object creation.anyways why maps you can use any collections to collect the user input. later u can iterate this collection and create object as you want – vikeng21 Apr 06 '14 at 11:12
  • Why you want to let user choose the `object name`? Object name is something which the end-user shouldn't care (and not possible) – Marco Acierno Apr 06 '14 at 11:13
  • This is something that could be achieved with a macro (code-generating code). Java doesn't support macros. Seeing both your username and your question, I am wondering whether you are coming from a functional programming background? – Andreas Tasoulas Apr 06 '14 at 19:29

1 Answers1

2

It's not possible. Names of local variables are not even persistent in the compiled Class file. Names of fields are there, as it is the part of API, but you would have to modify the Class file runtime - and that is not what do you want.

With Hashtable, it may be done like this:

Hashtable<String, Person> hashtable = new Hashtable<>();
hashtable.put("student", new Person());

Then you may get your "variable" by:

Person person = hashtable.get("student");

When I guess what you are trying to do, this is some more helpful example:

import java.util.Hashtable;
import java.util.Scanner;

public class Test {
    public static class Person {
        public final String name;
        public final int    age;

        public Person(String name, int age) {
            this.name = name;
            this.age  = age;
        }

        @Override
        public String toString() {
            return "Name: " + name + ", age: " + age;
        }
    }

    public static class PersonsList {
        private Hashtable<String, Person> persons = new Hashtable<String, Test.Person>();

        public void addPerson(Person person) {
            this.persons.put(person.name, person);
        }

        public Person findPerson(String name) {
            return persons.get(name);
        }

        @Override
        public String toString() {
            return persons.toString();
        }
    }

    public static void main(String[] args) {
        PersonsList personsList = new PersonsList();
        Scanner     scanner     = new Scanner(System.in);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();

            if (line.equals("END")) {
                break;
            }

            try {
                String[] parts = line.split(" ");
                String name    = parts[0];
                int    age     = Integer.valueOf(parts[1]);

                personsList.addPerson(new Person(name, age));
            } catch (NumberFormatException e) {
                System.out.println("Age must be an decimal non-floating-point number.");
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("You must enter both name and age");
            }
        }

        scanner.close();
        System.out.println(personsList);
    }
}
tzima
  • 1,285
  • 1
  • 10
  • 23