Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

java - How do I print the variable name holding an object?

How do I print the variable name holding my object?

For example, I have:

myclass ob=new myclass()

How would I print "ob"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Objects don't have names, unless you happen to be using a class which allows each object to be given one (e.g. via a variable retrieved with getName()).

In particular, the name of any particular variable used to refer to an object is completely unknown to the object itself. So you can't do:

Object foo = new Object();
// There's no support for this
String name = foo.getName(); // expecting to get "foo"

(Bear in mind that several variables could all refer to the same object, and there don't have to be any named variables referring to an object.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...