14 类型信息

运行是识别对象和类的信息 两种方式
RTTI 假定编译时已经知道所有的类型
反射 运行时发现和使用类的信息

1 RTTI

//多态 创建一个具体的对象(Circle Square Triangle) 向上转型为Shape 忽略对象具体类型
//在后面程序中使用匿名的Shape引用

abstract class Shape {
    void draw() {
        System.out.println(this + ".draw()");
    }

    abstract public String toString();
}

class Circle extends Shape {
    public String toString() {
        return "Circle";
    }
}

class Square extends Shape {
    public String toString() {
        return "Square";
    }
}

class Triangle extends Shape {
    public String toString() {
        return "Triangle";
    }
}

public class Shapes {
    public static void main(String[] args) {
        List<Shape> shapeList = Arrays.asList(new Circle(), new Square(), new Triangle());
        for (Shape shape : shapeList)
            shape.draw();
    }
}

2 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("Gum");
        } catch (ClassNotFoundException e) {
            System.out.println("Couldn't find Gum");
        }
        System.out.println("After Class.forName(\"Gum\")");
        new Cookie();
        System.out.println("After creating Cookie");
    }
}
interface HasBatteries {
}

interface Waterproof {
}

interface Shoots {
}

class Toy {
    // Comment out the following default constructor
    // to see NoSuchMethodError from (*1*)
    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("FancyToy");
        } catch (ClassNotFoundException e) {
            System.out.println("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) {
            System.out.println("Cannot instantiate");
            System.exit(1);
        } catch (IllegalAccessException e) {
            System.out.println("Cannot access");
            System.exit(1);
        }
        printInfo(obj.getClass());
    }
}

2.1 类字面常量

class Initable {
    static final int staticFinal = 47;
    static final int staticFinal2 = ClassInitialization.rand.nextInt(1000);
    static {
        System.out.println("Initializing Initable");
    }
}

class Initable2 {
    static int staticNonFinal = 147;
    static {
        System.out.println("Initializing Initable2");
    }
}

class Initable3 {
    static int staticNonFinal = 74;
    static {
        System.out.println("Initializing Initable3");
    }
}

public class ClassInitialization {
    public static Random rand = new Random(47);

    public static void main(String[] args) throws Exception {
        Class initable = Initable.class;
        System.out.println("After creating Initable ref");
        // Does not trigger initialization:
        System.out.println(Initable.staticFinal);
        // Does trigger initialization:
        System.out.println(Initable.staticFinal2);
        // Does trigger initialization:
        System.out.println(Initable2.staticNonFinal);
        Class initable3 = Class.forName("Initable3");
        System.out.println("After creating Initable3 ref");
        System.out.println(Initable3.staticNonFinal);
    }
}

Java 14 类型信息的更多相关文章

  1. 《Java编程思想》笔记14.类型信息

    运行时类型信息使得你可以在运行时发现和使用类型信息,主要有两种方式: "传统的"RTTI,它假定我们在编译时已经知道了所有的类型: "反射"机制,它允许我们在运 ...

  2. Java编程思想——第14章 类型信息(一)

    运行时类型信息使得你可以在程序运行时发现和使用类型信息.Java是如何让我们在运行时识别对象和类的信息得呢? 主要有两种方式:1.传统RTTI,他假定我们在编译期间已经知道了所有类型:2.反射,它允许 ...

  3. Java编程思想——第14章 类型信息(二)反射

    六.反射:运行时的类信息 我们已经知道了,在编译时,编译器必须知道所有要通过RTTI来处理的类.而反射提供了一种机制——用来检查可用的方法,并返回方法名.区别就在于RTTI是处理已知类的,而反射用于处 ...

  4. Java 类型信息

    <Thinking in Java 4th>第14章 类型信息 运行时类型信息(Run-Time Type Identification)使得你可以在程序运行时发现和使用类型信息. 14. ...

  5. Java基础 -- 深入理解Java类型信息(Class对象)与反射机制

    一 RTTI概念 认识Claa对象之前,先来了解一个概念,RTTI(Run-Time Type Identification)运行时类型识别,对于这个词一直是 C++ 中的概念,至于Java中出现RT ...

  6. Java类型信息

    一.引言 最近在阅读<Java编程思想>,学习一下java类型信息,现在做一下总结.Java如何让我们在运行时识别对象和类的信息的.主要有两种方式:一种是传统的“RTTI”,它假定我们在编 ...

  7. Java编程思想之十四 类型信息

    第十四章 类型信息 运行时类型信息使得你可以在程序运行时发现和使用类型信息 14.1 为什么需要RTTI 面向对象编程中基本的目的是:让代码只操作对基类的引用. 多态: import java.uti ...

  8. JAVA类型信息——反射机制

    JAVA类型信息——反射机制 一.反射机制概述 1.反射机制:就是java语言在运行时拥有的一项自我观察的能力,java通过这种能力彻底了解程序自身的情况,并为下一步的动作做准备. 2.反射机制的功能 ...

  9. JAVA类型信息——Class对象

    JAVA类型信息——Class对象 一.RTTI概要 1.类型信息RTTI :即对象和类的信息,例如类的名字.继承的基类.实现的接口等. 2.类型信息的作用:程序员可以在程序运行时发现和使用类型信息. ...

随机推荐

  1. windows下TCP服务器和客户端的实现

      服务器   1.初始化 WSAStartup(..)   2.创建Socket s = Socket ( .. )   3.绑定端口 ret = bind ( ... )   4.监听 ret = ...

  2. 网站性能优化之CSS无图片技术:三角形

    1.使用CSS无图片技术,可以总结得到以下三个优点: 减少请求资源的大小: 减少http的请求个数: 提高可维护性. 一.CSS无图片技术,微博中有哪些实际应用呢? 通过上面的展示,我们可以看到,无图 ...

  3. 大型网站技术架构介绍--squid

    一.大型网站技术架构介绍 1.pv高  ip高 并发量 2.大型网站架构重点    1. 高性能:响应时间,TPS,系统性能计数器.缓存,消息队列等.     高可用性High Availabilit ...

  4. java提高篇---HashMap

    HashMap也是我们使用非常多的Collection,它是基于哈希表的 Map 接口的实现,以key-value的形式存在.在HashMap中,key-value总是会当做一个整体来处理,系统会根据 ...

  5. Js扩展方法ReplaceAll

    String.prototype.replaceAll = function (reallyDo, replaceWith, ignoreCase) { if (!RegExp.prototype.i ...

  6. 使用jquery构建Metro style 返回顶部

    个人一直对metro风格的东西情有独钟,偶然间在腾讯网看到一款小插件,蓝色Metro风格的,所以决定把它放到我的博客中,这样做应该不会有版权问题吧orz.. Complete code 后言 我把他原 ...

  7. VM安装失败

    出现:VMware安装失败 “Failed to create the requested registry key Key:installer Error:1021" 解决: 开始--运行 ...

  8. js与C++交互及C++解析json

    转载:http://zhidao.baidu.com/link?url=LLuWzwMmpfVcQeSGv1CrAfRXpnZaetm9xypqwMW6zxLhhKES-rITAsG0-Ku-bSMA ...

  9. 适配 iOS尺寸

    http://liumh.com/2015/10/21/ios-image-related-matching/ 苹果IPHONE 5主屏尺寸: 4英寸 屏幕尺寸: iPhone 6 Plus 5.5英 ...

  10. SqlSever基础 datepart函数 返回现在几点了

    镇场诗:---大梦谁觉,水月中建博客.百千磨难,才知世事无常.---今持佛语,技术无量愿学.愿尽所学,铸一良心博客.------------------------------------------ ...