This a question that is often asked by my students:
How to get the current class in Java ?
In the code below, instead of A.class, I want to something like "get the current class".
One of my student even invent a new syntax for that purpose this.class.
But guess what, the compiler doesn't like invented syntaxes.
How to get the current class in Java ?
In the code below, instead of A.class, I want to something like "get the current class".
One of my student even invent a new syntax for that purpose this.class.
But guess what, the compiler doesn't like invented syntaxes.
public class A {
public static void main(String[] args) {
System.out.println("current class " + A.class);
}
}
My standard answer was that there is no obvious way to do that.
In fact, there is a hacky way to get the current class using exception, stack trace element and Class.forName.
The way to combine those elements is left as an exercice to the reader.
In fact, there is a hacky way to get the current class using exception, stack trace element and Class.forName.
The way to combine those elements is left as an exercice to the reader.
This is no more true with JDK 7 which will include the JSR 292 API (java.dyn) .
This API provides, as a side effect, a way to get the current class.
This API provides, as a side effect, a way to get the current class.
import java.dyn.MethodHandles;
public class A {
public static void main(String[] args) {
System.out.println(MethodHandles.lookup().lookupClass());
}
}
MethodHandles.lookup() returns a Lookup object which is a factory of method handles.
The Lookup object embodies the class of the code that calls the method lookup().
This class will be used to check if the code has the right or not to create a method handle.
And You can retreive this class using the method lookupClass().
The Lookup object embodies the class of the code that calls the method lookup().
This class will be used to check if the code has the right or not to create a method handle.
And You can retreive this class using the method lookupClass().
See you soon for tips and tricks on JDK 7/JSR 292.
cheers,
Rémi
Rémi
No comments:
Post a Comment