1. Class 对象:

  • 所有的类都是在对其第一次使用的时候,动态加载到JVM中的。当程序创建第一个对类的静态成员的引用时,就会加载这个类。这说明构造器也是类的静态方法。即使在构造器之前并没有static关键字,这个类也会被加载。
  • java程序在它开始运行之前并非完全被加载。其各个部分是在必要时才加载的。
  • 类加载器的执行过程

    1、 类加载器首先检查这个类的Class对象是否已经加载。如果尚未加载,默认的类加载器就会根据类名查找.class文件。

    2、在这个类的字节码被加载是,他们会接收验证,以确保其没有被损坏。并且不包含不良代码。这时java中用于安全防范目的的措施之一。

    3、一旦某个类被加载,他就用来创建这个类的所有对象。

下面这个例子说明了一下两点:

1. 类何时被加载

2. 如何加载

package net.mindview.typeinfo;
/**
* 首先, 下面的每一个类都有一个静态的代码块.
* 这个代码块, 在类第一次被加载时执行。
* @author samsung
*
*/ 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. 以后都是从这个类中创建实例对象
new Candy(); System.out.println("After creating Candy!");
try {
//Class.forName 获取对象引用的一种方法.参数是类的全限定文件名. 返回值是一个Class对象的引用.
//如果Gum没有被加载, 那么这个类就会被加载.
//使用类加载器加载类Gum, 在第一次加载Gum时, 也会主动去加载Gum这个类, 以后就从这个类中创建实例.
Class.forName("Gum");
} catch (ClassNotFoundException e) {
System.out.println("Could`t find Gum");
} System.out.println("After Class.forName(\"Gum\")");
new Cookie();
System.out.println("After creating Cookie"); //这个例子展示, 第二次实例化Cookie是, static静态代码块没有被再次执行, 它只会在第一次加载时执行.
new Cookie();
System.out.println("After creating Cookie twice"); }
}
  • 下面展示如何通过Class来发现整个类的基本结构. 详细看代码注释

    package net.mindview.typeinfo.toys;
    
    /**
    * 以下:展示了完全的获取一个类的完整的继承结构.
    * @author samsung
    *
    */
    interface HasBatteries {}
    interface Waterproof {}
    interface Shoots {} class Toy{
    Toy(){}
    Toy(int i){}
    } class FancyToy extends Toy implements HasBatteries, Waterproof, Shoots{
    FancyToy() {super();}
    } public class ToyTest {
    static void printInfo(Class cc){
    /**
    * 这里调用了Class的一些基本方法
    * cc.isInterface(): 是接口么
    * cc.getSimpleName(): 类名, 不含路径
    * cc.getCanonicalName(): 全限定类名
    */
    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("net.mindview.typeinfo.toys.FancyToy");
    } catch (ClassNotFoundException e) {
    System.out.println("Can`t find FancyToy");
    System.exit();
    } printInfo(c);
    System.out.println();
    /**
    * c.getInterfaces(): 获取这个类已继承的所有的接口
    */
    for(Class face: c.getInterfaces()){
    //打印接口类
    printInfo(face);
    System.out.println();
    } /**
    * c.getSuperclass(): 获取这个类的父类
    */
    Class up = c.getSuperclass();
    Object obj = null;
    try {
    //将父类实例化
    //使用newInstance来实例化的类不许带有一个默认的构造器
    obj = up.newInstance();
    } catch (InstantiationException e) {
    System.out.println("Can`t instantiate");
    System.exit();
    } catch (IllegalAccessException e) {
    System.out.println("Can`t instantiate");
    System.exit();
    }
    //打印父类基本细腻
    printInfo(obj.getClass());
    } }

    运行结果:

    Class name:net.mindview.typeinfo.toys.FancyToy is interface ? [false]
    Simple name: FancyToy
    Canonical name: net.mindview.typeinfo.toys.FancyToy Class name:net.mindview.typeinfo.toys.HasBatteries is interface ? [true]
    Simple name: HasBatteries
    Canonical name: net.mindview.typeinfo.toys.HasBatteries Class name:net.mindview.typeinfo.toys.Waterproof is interface ? [true]
    Simple name: Waterproof
    Canonical name: net.mindview.typeinfo.toys.Waterproof Class name:net.mindview.typeinfo.toys.Shoots is interface ? [true]
    Simple name: Shoots
    Canonical name: net.mindview.typeinfo.toys.Shoots Class name:net.mindview.typeinfo.toys.Toy is interface ? [false]
    Simple name: Toy
    Canonical name: net.mindview.typeinfo.toys.Toy

    总结: 

    • cc.isInterface(): 是接口么

    • cc.getSimpleName(): 类名, 不含路径

    • cc.getCanonicalName(): 全限定类名

    • c.getInterfaces(): 获取这个类已继承的所有的接口
    • c.getSuperclass(): 获取这个类的父类
    • 使用newInstance来实例化的类不许带有一个默认的构造器

2. 类字面常量

  Toy.class

  • 所有的类都有类字面常量,普通类, 接口,数组,以及基本数据类型。
  • 使用 .class创建一个Class对象的引用时,不会自动初始化该Class对象,这个加载过程包括以下三步
    1. 加载。 由类加载器执行。该步骤将查找字节码,通常在classpath所制定的路径中查找,并从这些字节码中创建一个class对象。
    2. 链接:验证类中的字节码,为静态域分配存储空间。并且,如果必要的话,会解析这个类创建的对其他类的所有引用。
    3. 初始化:如果该类具有超类,则对其初始化。执行静态初始化构造器或者静态初始化代码块。。初始化的过程将会被延迟,直到对静态方法或者非常数静态域进行首次引用时才执行初始化。(注意:类构造器其实就是隐式的静态方法)
      package net.mindview.typeinfo;
      
      import java.util.Random;
      
      class Initable{
      //常数
      static final int staticFinal = ;
      //静态常量
      static final int staticFinal2 = ClassInitialization.rand.nextInt();
      //静态代码块
      static {
      System.out.println("Initializing Initable");
      }
      } class Initable2{
      //非常数静态变量
      static int staticNonFinal = ;
      static {
      System.out.println("Initializing Initable2");
      }
      } class Initable3{
      //非常熟静态变量
      static int staticNonFinal = ;
      static {
      System.out.println("Initializing Initable3");
      }
      } public class ClassInitialization {
      public static Random rand = new Random();
      public static void main(String[] args) throws ClassNotFoundException {
      //下面这句话执行完,并没有对Initable这个类进行初始化.
      Class initable = Initable.class; System.out.println("创建Initable引用之后");
      //没有触发初始化---Initable.staticFinal是一个常数, 所以不会触发初始化
      System.out.println(Initable.staticFinal);
      System.out.println("-------1----------");
      //触发初始化 -- Initable.staticFinal2是引用常数, 触发初始化
      System.out.println(Initable.staticFinal2);
      System.out.println("---------2--------");
      //触发初始化---Initable2.staticNonFinal非常数静态域, 调用后会触发初始化
      System.out.println(Initable2.staticNonFinal);
      System.out.println("---------3--------");
      //执行Class.forName的时候, 会将对象初始化.
      Class initable3 = Class.forName("net.mindview.typeinfo.Initable3");
      System.out.println("创建Initable3引用后");
      System.out.println("---------4--------");
      System.out.println(Initable3.staticNonFinal); } }

      结果运行:

      创建Initable引用之后
      
      -----------------
      Initializing Initable -----------------
      Initializing Initable2 -----------------
      Initializing Initable3
      创建Initable3引用后
      -----------------

      详细看这个demo. 里面主要说了几点

      1. .class方式构造的对象的实例化会延迟
      2. 静态常量的调用不会触发实例化
      3. 非静态常量的调用会触发实例化.
      4. class.forName()会立即触发初始化

3.  泛化的class引用

  • 我们使用通配符堆Class类进行泛型化, 通配符是 ? ,表示“任何事物”,例如:
package net.mindview.typeinfo;

public class WildcardClassReferences {

    public static void main(String[] args) {
/**
* Class<?> 使用的时通配符来表示泛型.
*/
Class<?> clazz = int.class;
clazz = double.class; } }
  • 创建限定某种类型的Class, 可以使用?extends Number形式。

    package net.mindview.typeinfo;
    
    public class BoundedClassReferences {
    
        public static void main(String[] args) {
    Class<? extends Number> clazz = int.class;
    clazz = double.class;
    //下面这句话就是报编译异常, 因为String 不是Number的一类
    //clazz = String.class;
    }
    }
  • 使用泛型类存储一个类。如下例:
    package net.mindview.typeinfo;
    
    import java.util.ArrayList;
    import java.util.List; /**
    * 定义一个IntegerCounted类--Integer计数器
    */
    class CountedInteger {
    //计数器总数
    private static long counter;
    //每一个计数类的编号
    private final long id = counter ++;
    //打印计数器编号
    public String toString(){return Long.toString(id);};
    } public class FilledList<T> {
    //这里定义一个类型, 表示该类是处理拿一个特定类型的, 在实例化的时候, 传递实际类型
    Class<T> type;
    public FilledList(Class<T> type){
    this.type = type;
    } public List<T> create(int number) throws InstantiationException, IllegalAccessException{
    List<T> list = new ArrayList<T>();
    for(int i=; i<number; i++){
    list.add(type.newInstance());
    }
    return list;
    }
    public static void main(String[] args) {
    try {
    FilledList<CountedInteger> fl = new FilledList(CountedInteger.class);
    List<CountedInteger> list = fl.create();
    //打印list集合,就是调用list集合中每个元素的toString方法
    System.out.println(list);
    } catch (InstantiationException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    }
    } }
  • 如果你知道某个具体类, 想获得这个具体类的超类, 使用“”?super 具体类“的方式实现,如下例:
    package net.mindview.typeinfo.toys;
    
    /**
    * 以下:展示了完全的获取一个类的完整的继承结构.
    * @author samsung
    *
    */
    interface HasBatteries {}
    interface Waterproof {}
    interface Shoots {}
    interface other {} class Toy{
    Toy(){}
    Toy(int i){}
    } class FancyToy extends Toy implements HasBatteries, Waterproof, Shoots, other{
    FancyToy() {super();}
    } public class ToyTest {
    static void printInfo(Class cc){
    /**
    * 这里调用了Class的一些基本方法
    * cc.isInterface(): 是接口么
    * cc.getSimpleName(): 类名, 不含路径
    * cc.getCanonicalName(): 全限定类名
    */
    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("net.mindview.typeinfo.toys.FancyToy");
    } catch (ClassNotFoundException e) {
    System.out.println("Can`t find FancyToy");
    System.exit();
    } printInfo(c);
    System.out.println();
    /**
    * c.getInterfaces(): 获取这个类已继承的所有的接口
    */
    for(Class face: c.getInterfaces()){
    //打印接口类
    printInfo(face);
    System.out.println();
    } /**
    * c.getSuperclass(): 获取这个类的父类
    */
    Class up = c.getSuperclass();
    Object obj = null;
    try {
    //将父类实例化
    //使用newInstance来实例化的类不许带有一个默认的构造器
    obj = up.newInstance();
    } catch (InstantiationException e) {
    System.out.println("Can`t instantiate");
    System.exit();
    } catch (IllegalAccessException e) {
    System.out.println("Can`t instantiate");
    System.exit();
    }
    //打印父类基本细腻
    printInfo(obj.getClass());
    } }
    package net.mindview.typeinfo.toys;
    
    public class GenericToyTest {
    
        public static void main(String[] args) throws InstantiationException, IllegalAccessException {
    Class<FancyToy> ftClass = FancyToy.class;
    FancyToy fancyToy = ftClass.newInstance();
    //如果你想得到某个实现类的超类, 那么他的Class应该如何写呢?
    Class<? super FancyToy> up = ftClass.getSuperclass();
    //Class<Toy> up1 = ftClass.getSuperclass();
    Object obj = up.newInstance();
    }
    /**
    * 这里FancyToy的超类是Toy. 而我想得到Toy这个超类, 并不能直接这样写
    * Class<Toy> up = ftClass.getSuperclass();
    * 这样编译不通过.
    */
    }
  • 使用instanceof判断类型. 最好在进行向下转型时, 都是用instanceof进行判断
    package net.mindview.typeinfo;
    
    import net.mindview.initialization.Dog;
    
    /**
    * 类型判断
    */
    public class InstanceofTest { public static void main(String[] args) {
    //这里就是对x的类型进行的判断
    if("x" instanceof String){
    //执行String类型的方法
    }
    }
    }

4. 反射

  • getMethods()方法,获取的时整个继承树中的全部方法
  • getConstructors()方法,获取的是所有的构造器
  • 可以通过解析对象所代表的方法, 并获取其名字, 返回值, 参数等信息.
  • 也可以使用toString()方法, 返回的是包含有完整方法特征信息的字符串. 包括 返回值,返回类型,参数等.
    package net.mindview.typeinfo;
    
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Method;
    import java.util.regex.Pattern; public class ShowMethods {
    private static String usage = ""
    + "usage:\n"
    + "ShowMethods qualified.class.name\n"
    + "To show all methods in class or:\n"
    + "ShowMethods qualified.class.name. word\n"
    + "To search for methodds invoiving 'word'"; private static Pattern p = Pattern.compile("\\w+\\."); public static void main(String[] args) {
    if(args.length<){
    System.out.println(usage);
    System.exit();
    } int lines = ;
    try {
    Class<?> c = Class.forName(args[]);
    //getMethods获取的是整个继承树中所有的方法
    Method[] methods = c.getMethods();
    //获取已有的构造器
    Constructor[] ctors = c.getConstructors(); if(args.length == ){
    //打印所有继承树中的方法名
    for(Method method: methods){
    System.out.println(p.matcher(method.toString()).replaceAll(""));
    }
    //打印全部构造器
    for(Constructor ctor: ctors){
    System.out.println(p.matcher(ctor.toString()).replaceAll(""));
    }
    lines = methods.length + ctors.length;
    }else {
    //打印指定类中的方法
    for(Method method: methods){
    if(method.toString().indexOf(args[]) != -){
    System.out.println(p.matcher(method.toString()).replaceAll(""));
    lines++;
    }
    }
    //打印构造器
    for(Constructor ctor :ctors){
    if(ctor.toString().indexOf(args[])!=-){
    System.out.println(p.matcher(ctor.toString()).replaceAll(""));
    lines++;
    }
    }
    } } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }
    } }

    输入参数

    net.mindview.typeinfo.ShowMethods

    运行结果:

    public static void main(String[])
    public final void wait(long,int) throws InterruptedException
    public final native void wait(long) throws InterruptedException
    public final void wait() throws InterruptedException
    public boolean equals(Object)
    public String toString()
    public native int hashCode()
    public final native Class getClass()
    public final native void notify()
    public final native void notifyAll()
    public ShowMethods()

    输入参数

    net.mindview.typeinfo.ShowMethods
    net.mindview.typeinfo.ShowMethods

    运行结果

    public static void main(String[])
    public ShowMethods()

java编程思想第四版第十四章 类型信息总结的更多相关文章

  1. Java编程思想(第4版) 中文清晰PDF完整版

    Java编程思想(第4版) 中文清晰PDF完整版 [日期:2014-08-11] 来源:Linux社区  作者:Linux [字体:大 中 小]     <Java编程思想>这本书赢得了全 ...

  2. 20190908 On Java8 第十九章 类型信息

    第十九章 类型信息 RTTI(RunTime Type Information,运行时类型信息)能够在程序运行时发现和使用类型信息. Java 主要有两种方式在运行时识别对象和类信息: "传 ...

  3. 关于 java编程思想第五版 《On Java 8》

    On Java 8中文版 英雄召集令 这是该项目的GITHUB地址:https://github.com/LingCoder/OnJava8 广招天下英雄,为开源奉献!让我们一起来完成这本书的翻译吧! ...

  4. java编程思想第四版第十四章 类型信息习题

    fda dfa 第三题u package net.mindview.typeinfo.test4; import java.util.ArrayList; import java.util.Array ...

  5. Java编程思想 4th 第2章 一切都是对象

    Java是基于C++的,但Java是一种更纯粹的面向对象程序设计语言,和C++不同的是,Java只支持面向对象编程,因此Java的编程风格也是纯OOP风格的,即一切都是类,所有事情通过类对象协作来完成 ...

  6. 重新精读《Java 编程思想》系列之组合与继承

    Java 复用代码的两种方式组合与继承. 组合 组合只需将对象引用置于新类中即可. 比如我们有一个B类,它具有一个say方法,我们在A类中使用B类的方法,就是组合. public class B { ...

  7. JAVA编程思想(第四版)学习笔记----4.8 switch(知识点已更新)

    switch语句和if-else语句不同,switch语句可以有多个可能的执行路径.在第四版java编程思想介绍switch语句的语法格式时写到: switch (integral-selector) ...

  8. java编程思想第四版中net.mindview.util包下载,及源码简单导入使用

    在java编程思想第四版中需要使用net.mindview.util包,大家可以直接到http://www.mindviewinc.com/TIJ4/CodeInstructions.html 去下载 ...

  9. 《Java编程思想第四版》附录 B 对比 C++和 Java

    <Java编程思想第四版完整中文高清版.pdf>-笔记 附录 B 对比 C++和 Java “作为一名 C++程序员,我们早已掌握了面向对象程序设计的基本概念,而且 Java 的语法无疑是 ...

随机推荐

  1. npm install bcrypt报错

    gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env va ...

  2. python学习-并发编程(十四)

    14.2线程的创建与启动 import threading # 定义一个普通的action函数,该函数准备作为线程执行体 def action(max): for i in range(max): p ...

  3. Linux面试题-8

    1.Linux文件系统的文件都按其作用分门别类地放在相关的目录中,对于磁盘这种外部设备文件,一般应将其放在(C)目录中. A./bin B./etc C./dev D./lib 2.当使用mount进 ...

  4. ESP8266开发之旅 进阶篇⑤ 代码规范 —— 像写文章一样优美

    1.前言     之前,一直在跟大伙分享怎么去玩蓝牙模块,怎么去玩wifi模块,怎么去玩json,然后有很多小伙伴就留言各种问题或者说直接怼他的代码过来让我看,然后我就一脸懵逼(代码中到处各种abcd ...

  5. GO基础之流程控制语句

    一.if分支语句 if 布尔表达式 1 { /* 在布尔表达式 1 为 true 时执行 */ } ; a% == { fmt.Println("偶数") } if 布尔表达式 1 ...

  6. windows下Python开发错误记录以及解决方法

    windows下使用pip提示ImportError: cannot import name 'main' 原因:将pip更新为10.0.0后库里面的函数有所变动造成这个问题 解决方法:先卸载现在的p ...

  7. uni-app 请求封装

    1.创建一个http.js ​ const baseUrl = 'http://192.168.1.188:8080'; const httpRequest = (opts, data) => ...

  8. css伪类选择器的查找顺序

    当伪类选择器last-child.first-child无效时,就是因为不了解css伪类选择器的查找顺序造成选中某一元素失败. 先给出一段dom <body> <div>第一个 ...

  9. Spring(四)Spring与数据库编程

    Spring最重要的功能毫无疑问就是操作数据.数据库的百年城是互联网编程的基础,Spring为开发者提供了JDBC模板模式,那就是它自身的JdbcTemplate.Spring还提供了Transact ...

  10. swiper轮播

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...