February 01, 2011
Mark Wielaard: New GPG key.
Finally created a new GPG key using gnupg. The old one was a DSA/1024 bits one and 8 years old. The new one is a RSA/2048 bits one. I will use the new one in the future to sign any release tarballs I might create. pub 2048R/57816A6A 2011-01-29 Key f...
More »
February 01, 2011
Andrew Hughes: [SECURITY] IcedTea6 1.7.8, 1.8.5, 1.9.5 Released!.
We are pleased to announce a new set of security releases, IcedTea6 1.7.8, IcedTea6 1.8.5 and IcedTea6 1.9.5.
This update contains the following security updates:
The IcedTea project provides a harness to build the source code from OpenJDK6 u...
More »
December/2024
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | | | | |
|
|
How to get the current class in Java ?
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.
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.
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.
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().
See you soon for tips and tricks on JDK 7/JSR 292.
cheers,
Rémi
Date: October, 26 2010
Url: http://www.java.net/blog/forax/archive/2010/10/26/how-get-current-class-java
Others News
|