在Java中获取对象名称 [英] Get object name in Java
问题描述
如何获取对象名称?例如
Objet o = new Object();
我想得到这个o并打印出来。
如果你想拥有你创建的对象的标识符,你可以简单地拥有一个对象实例,它包含你创建的每个对象的标识符。 / p>
例如,如果你有一个名为 Car
的类,那么该类可以有一个字符串
名为id的变量,可以与创建的每个Car对象一起使用,为该对象提供标识符。例如,
class Car
{
private String id;
public Car(String id)
{
this.id = id;
}
}
然后现在当你创建一个Car对象时,你会通过该对象到构造函数的唯一标识符:
Car car1 = new Car(c1);
如果你想获得每辆车的id,你可以使用getter方法返回特定汽车对象的id字段。例如:
public String getId()
{
return id;
}
然后你可以通过这样做获得car1的id:
System.out.println(car1.getId());
希望这是你想要的。
How can I get an object name? For example
Objet o = new Object();
I want to get this "o" and print it.
If you want to have an identifier for an object that you create, you can simply have an instance of your object that holds the identifier of each object you create.
For example if you have a class called Car
, then that class can have a String
variable called id, which can be used with each Car object created to give that object an identifier. E.g.
class Car
{
private String id;
public Car(String id)
{
this.id = id;
}
}
Then now when you create a Car object, you pass a unique identifier for that object to the constructor:
Car car1 = new Car("c1");
If you then want to get the id of each car, you get use a getter method that return the id field of a specific car object. For example:
public String getId()
{
return id;
}
then you can get the id of car1 by doing this:
System.out.println(car1.getId());
Hope this is what you're looking for.
这篇关于在Java中获取对象名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!