Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12141

How to get a variable name in the caller class? [closed]

$
0
0

I would like to have a debugging aid, telling me in what instance of an own class the error happened.

public class MyApp {    MyClass myClass1= new MyClass(...);    MyClass myClass2= new MyClass(...);    MyClass myClassN= new MyClass(...);}

So MyClass should tell me, whether it is instance myClass1, myClass2 or myClassN which is causing the error.

I have found examples how to access a caller class and how to access variable names via reflection. But in order to use Class.getDeclaredField(String name) you have to know the name of the variable beforehand.

I could, of course, pass the instance name as a string, but if the name could be elicited with code, it would not only be nicer, but also a help in future unforeseen bugs.

From your comments I see that I should have given some more details. So MyClass doesn't occur in a loop, but is an extended "service providing" JTextField, which is used for various input and each instance has a meaningful name. Since any user input is error prone, I try to detect as many errors as I can figure out and signal the user for correction. So far there are no crashes (stacktrace), but there might be cases which will be termed legal, but I was not aware of in the now starting test phase. If the TextField's variable name is given in the error message and a member of the testing team denies the validity of my error message, he could just copy the error message and his input and send it to me for further inspection.

Thanks, Akhilesh, for your code. I mentioned this solution in my question.


Viewing all articles
Browse latest Browse all 12141

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>