Get object name of a class from the user in Java
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
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);
}
}
链接地址: http://www.djcxy.com/p/23650.html
上一篇: 如何将变量和数据从PHP传递到JavaScript?
下一篇: 在Java中获取用户的类的对象名称