×

Loading...

Jabber's toy code---003---class literals

本文发表在 rolia.net 枫下论坛If you are a Java programmer, you will frequently see a word---literal. In Java, literals mean something you can create directly, instead of using key word "new". All the priminitive data are literals. In addition, String can be created as literals, such as "hello" and "1323".

Not many Java programmers know the class literals. It meas that one can get the Class type for a data type (class or priminitve data type) by using .class syntax. Here is an example from which one can see how to use class literals

public class Test{

public static void main(String[] args) {
Class[] cls= new Class[] {String.class, java.awt.Button.class, int.class, Integer.class, javax.ejb.EJBObject.class, com.xyz.Cart.class};
for(int i=0; i<cls.length; i++) {
System.out.println(i + ": " + cls[i].getName());
}
}
}

The above toy code can be useful in real project. A good example is as follows: You are asked to create an object classification programm. The first thing you need to do is to create a container (Array? Vector? Set? ..) to hold all the possible data types, nee, Class objects. In such a context, the class literal is a convenience for us to get the Class objects.

Hope this helps.更多精彩文章及讨论,请光临枫下论坛 rolia.net
Sign in and Reply Report