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

jabber (jabber)
<本文发表于: 相约加拿大:枫下论坛 www.rolia.net/f >
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.
<本文发表于: 相约加拿大:枫下论坛 www.rolia.net/f >

2001-6-25 -04:00

回到话题: Jabber's toy code---003---class literals

回到论坛: HOME枫下论坛枫下论坛主坛工作学习IT杂谈