Answer» How can I find out at run time what java class I am in. Or what java class called me?
thank you.A
In every single class (code) you are in just write a code that will output the INFORMATIONS that is related to the class Easy i dont know why you want to do that?use reflection.Thanks for the replies. Let me explain the actual problem. I have a main method which reads a FILE and passes the data to a class whose name is a state code. ie AZ, DE,MA etc. Each of these state classes write out data that USES the state code. Each of these state classes is coded by a different person and currently they each have a statement in them that reads:
theState = "xx"; where xx is the name of the class. What I am trying to avoid is one of the programmers using the wrong state code when it is just the name of the class.
what I have come up with is the following method:
private static String myName() { String className; int i = 0; className = "A"; try { int ii = 1 / i; } catch (Exception e) { StackTraceElement[] se = e.getStackTrace(); String fullClassName = se[1].getClassName(); int lastDot = fullClassName.lastIndexOf("."); className = fullClassName.substring(++lastDot); } return className; }
Is there a simpler way of doing this. I look up reflection but couldn't figure out how to use it.
Thanks for any help. what about this.getClassName() instead of purposely causing an error, getting a stack trace and GRABBING the top object?
or am I missing something?this.getClassName() will not compile. I got it to compile. Thanks EVERYONE.
|