14章类型信息---class对象

//: typeinfo/toys/ToyTest.java
// Testing class Class.
package typeinfo.toys;
import static net.mindview.util.Print.*;


interface HasBatteries {}
interface Waterproof {}
interface Shoots {}


class Toy {
  Toy() {}
  Toy(int i) {}
}


class FancyToy extends Toy
implements HasBatteries, Waterproof, Shoots {
  FancyToy() { super(1); }
}


public class ToyTest {
  static void printInfo(Class cc) {
    print("Class name: " + cc.getName() +
//getName方法是带包名的类名
      " is interface? [" + cc.isInterface() + "]");//isInterface方法是否是接口
    print("Simple name: " + cc.getSimpleName());//getSimpleName方法不带包名的简单类名

    print("Canonical name : " + cc.getCanonicalName());

//getCanonicalName方法是产生全限定的类名,也就是带包名的类名,canonical[kə'nɒnɪk(ə)l] [kə'nɑnɪkl]规范化,标准的; 典范的

  }
  public static void main(String[] args) {
    Class c = null;
    try {
      c = Class.forName("typeinfo.toys.FancyToy");
    } catch(ClassNotFoundException e) {
      print("Can't find FancyToy");
      System.exit(1);
    }
    printInfo(c);
    for(Class face : c.getInterfaces())
      printInfo(face);
    Class up = c.getSuperclass();
    Object obj = null;
    try {
      // Requires default constructor:
      obj = up.newInstance();
    } catch(InstantiationException e) {
      print("Cannot instantiate");
      System.exit(1);
    } catch(IllegalAccessException e) {
      print("Cannot access");
      System.exit(1);
    }
    printInfo(obj.getClass());
  }

}

//如果去掉默认的构造器的话,调用up.newInstance();就会报无法实例化的错

你可能感兴趣的:(java编程思想)