首先我们来看一个使用Class类的例子。
我们可以通过对象的getClass()方法得到一个Class对象,如下:
package com.freesoft.javaadvanced; import com.freesoft.testentity.Olive; public class TestClassClass { public static void main(String[] args) { Olive o = new Olive("Kalamara", Olive.BLACK); // c是一个Class类的对象,这个对象的属性中我们能够得到类名等信息 Class<?> c = o.getClass(); System.out.println(c); System.out.println(c.getName()); System.out.println(c.getSimpleName()); } }
package com.freesoft.javaadvanced; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import com.freesoft.testentity.Olive; public class TestClassClass { public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Olive o = new Olive("Kalamara", Olive.BLACK); // c是一个Class类的对象,这个对象的属性中我们能够得到类名等信息 Class<?> c = o.getClass(); System.out.println(c); System.out.println(c.getName()); System.out.println(c.getSimpleName()); // 得到Olive这个类的所有构造函数,由于可能有多个构造函数,所以返回值是个数组 // 数组的每个元素都是一个Constructor<?>类型 Constructor<?>[] constractors = c.getConstructors(); System.out.println("Number of constructors: " + constractors.length); for (Constructor<?> constructor : constractors) { System.out.println(constructor); } // 通过Constructor<T>对象创建对象实例 Object obj = constractors[0].newInstance("Kalamara", 0x0000FF); System.out.println(obj); } }
package com.freesoft.javaadvanced; import java.lang.reflect.InvocationTargetException; import com.freesoft.testentity.Olive; public class TestClassClass { public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Olive o = new Olive("Kalamara", Olive.BLACK); // c是一个Class类的对象,这个对象的属性中我们能够得到类名等信息 Class<?> c = o.getClass(); while (!c.getSimpleName().equals("Object")) { System.out.println(c.getName()); c = c.getSuperclass(); } } }