2009年1月18日

Primitive Class


import java.util.*;
import java.lang.reflect.Array;
import static java.lang.System.out;

public class Main {

static Map<String, Class<?>> primitiveClass = new HashMap<String, Class<?>>();
static {
primitiveClass.put("boolean", Boolean.TYPE);
primitiveClass.put("byte", Byte.TYPE);
primitiveClass.put("char", Character.TYPE);
primitiveClass.put("short", Short.TYPE);
primitiveClass.put("int", Integer.TYPE);
primitiveClass.put("long", Long.TYPE);
primitiveClass.put("float", Float.TYPE);
primitiveClass.put("double", Double.TYPE);
}

public static Class<?> findClass(String className) throws ClassNotFoundException {
Class<?> c =primitiveClass.get(className);
if (c == null)
c = Class.forName(className);
return c;
}

private static void printArrayClass(Class<?> componentType) {
Object array = Array.newInstance(componentType, 0);
out.println(array.getClass().getCanonicalName());
}

public static void main(String[] args) throws ClassNotFoundException {

Class<?>[] classes = new Class[] {int.class, Integer.TYPE, Integer.class};
for (Class<?> c : classes) {
printArrayClass(c);
}
out.println();

String[] cns = new String[]{"int", "java.lang.Integer"};
for (String c : cns) {
printArrayClass(findClass(c));
}

}
}
/*
int[]
int[]
java.lang.Integer[]

int[]
java.lang.Integer[]
*/

沒有留言:

網誌存檔