static "this" or discovering the calling method name and class

Sep 06, 2006 00:03

The following link describes a mechanism to programmatically determine the current location in a program.

http://java.sun.com/developer/JDCTechTips/2003/tt0318.html#2

A new feature in J2SE version 1.4 is the Chained Exception Facility

Throwable t = new Throwable();
StackTraceElement elements[] = t.getStackTrace();
String method = elements[0].getMethodName();
System.out.println("Method: " + method);

You simply call the new getStackTrace method of Throwable. This returns an array of StackTraceElement objects, which give full access to class and method information in the chain.

I intend to use it for instantiating static MD variables to replace the current way

public static final MD X = new MD(GeoPoint.class, "x");
public static final MD Y = new MD(GeoPoint.class, "y");
public static final MD Z = new MD(GeoPoint.class, "z");

with the new way:

public static final MD X = new MD("x");
public static final MD Y = new MD("y");
public static final MD Z = new MD("z");

where the MD constructor figures out which class it was called from using the method described above.

public MD(String reflectionDescription)
{
initialize(ClassHelper.getClass(new Throwable().getStackTrace()[1].getClassName()), reflectionDescription);
}
Previous post Next post
Up