/**
* @author E-mail:
* @version 2018年5月31日 下午8:58:40
*
* (RTTI, Run-Time Type Identification)是Java中非常有用的机制,在Java运行时,RTTI维护类的相关信息。
多态(polymorphism)是基于RTTI实现的。RTTI的功能主要是由Class类实现的
*/
class Candy{
static {System.out.println("Loading Candy");}
}
class Gum {
static {System.out.println("Loading Gum");}
}
class Cookie{
static {System.out.println("Loading Cookie");}
}
public class SweetShop {
public static void main(String[] args) {
System.out.println("inside main");
new Candy();
System.out.println("After creating Candy");
try{
/**
* Class.forName():取得Class对象引用的一种方法;
* 如果找不到要加载的类,它会抛出异常ClassNotFoundException
*/
Class.forName("com.aijie.typeinfo.Gum");
}catch(ClassNotFoundException e){
//e.printStackTrace();
System.out.println("Couldnt find Gum");
}
System.out.println("After Class.forName(\"Gum\")");
new Cookie();
System.out.println("After creating Cookie");
}
}
package com.aijie.typeinfo.toys;
/**
* @author E-mail:
* @version 2018年5月31日 下午9:28:07
* 注意,在传递给forName()的字符串中,必须使用全限定名(包含包名)
* 使用getSimpleName() ; getCanonicalName()来产生不含包名的类名和全限定的类名
* isInterface()可以告诉这个Class对象是否表示某个接口
* Class.getInterfaces()方法返回Class对象,它表示在感兴趣的Class对象中所包含的接口
* getSuperclass()可以直接查询其基类
*
* Class 的newInstance()方法是实现虚拟构造器的一种途径,虚拟构造器允许声明:
* 我不知道你的确切类型,但是无论如何你要正确的创建自己。在实例中,up仅仅是一个Class的引用,
* 在编译期不具备任何更进一步的类型信息。当创建新的实例时,会得到Object的引用,但是这个引用指向Toy对象。
* 使用newInstance()来创建的类,必须带有默认的构造器
*/
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){
System.out.println("Class name:"+cc.getName()+"is interface?["+cc.isInterface()+"]");
System.out.println("Simple name:"+cc.getSimpleName());
System.out.println("Canonical name:"+cc.getCanonicalName());
}
public static void main(String[] args) {
Class c = null;
try{
c = Class.forName("com.aijie.typeinfo.toys.FancyToy");
}catch(ClassNotFoundException e){
System.out.println("cant find FancyToy");
System.exit(1);
}
printInfo(c);
for(Class face : c.getInterfaces()){
printInfo(face);
}
Class up = c.getSuperclass();
Object obj = null;
try{
obj = up.newInstance();
}catch(InstantiationException e){
System.out.println("cannot instantiate");
System.exit(1);
}catch(IllegalAccessException e){
System.out.println("cannot access");
System.exit(1);
}
printInfo(obj.getClass());
}
}