java 获取对象的类名称,从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 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 persons = new Hashtable();

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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值