this question has answer here:
- get object name in java [closed] 1 answer
i know if can name of instance name in java. example:
class { public void run() { system.out.println("name: " + ????); } } public class main { public static void main(string[] _args) { p = new a(); q = new a(); p.run(); q.run(); } }
my expectation result be:
name: p name: q
is anyway this?
that's impossible in java, not available through reflection. best bet have string
field store name of variable , fill field when creating object reference.
class { private final string name; public a(string name) { this.name = name; } public void run() { system.out.println("name: " + this.name); } } //... p = new a("p"); q = new a("q");