/* * Constructor. Only the Java Virtual Machine creates Class * objects. */ private Class() {} Class類的構造函數是私有的,只有jvm能new Class 不能 new Class<Cat>();
/** * Run Time Type Information */ public class Client { public static void main(String[] args) { Object obj = new Client(); /**class com.RTTI.test.Client*/ System.out.println(obj.getClass()); System.out.println(obj.getClass().getName()); System.out.println(int.class); Class<Integer> genri = int.class; genri = Integer.class; /** * error:Type mismatch: cannot convert from Class<Integer> to Class<Number> * Class<Number> genericNameer = int.class; */ Class<?> generic = int.class; /** * 接受繼承自Number的類型 的 class,而不是繼承與Number.class的 Class類型 */ Class<? extends Number> bounded = int.class; Building b = new House(); Class<House> houseType = House.class; houseType.cast(b); ClassTest(houseType); } public static void ClassTest(Class<? extends House> clazz) { try { Object obj = clazz.newInstance(); if(obj instanceof House) { System.out.println("obj instanceof House=true"); House house = clazz.cast(obj); house.ff(); }else if(obj instanceof Building) { System.out.println("obj instanceof Building=true"); Building b = (Building)obj; b.f(); } if(clazz.isInstance(obj)) { System.out.println("House Instance"); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } class Building{ public void f() { System.out.println("Building f()"); } } class House extends Building{ @Override public void f() { System.out.println("House f()"); } public void ff() { System.out.println("House ff()"); } };