易学笔记--从0开始学JAVA(个人纯手工笔记共享 免费!免费!免费!)--比直接看书快N倍的速度掌握知识点--第14章 类型信息

 

第14章 类型信息/14.1 为什么需要RTTI

标签:作者:易学笔记  更多资料请联系微信或QQ:1776565180

 

  • 为什么需要RTTI
  1. 什么是RTTI:RTTI是Run-Time Type Information(通过运行时类型信息 ),也就是在运行时使用和发现类的信息
  2. 源代码:

    package typeinfo;

    //: typeinfo/Shapes.java

    import java.util.*;

    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();

    }

    /* Output:

    Circle.draw()

    Square.draw()

    Triangle.draw()

    *///:~

  3. 结果输出:

    Circle.draw()

    Square.draw()

    Triangle.draw()


第14章 类型信息/14.2 Class对象

标签:作者:易学笔记  更多资料请联系微信或QQ:1776565180

 

  • Class对象
  1. 概念:用于表示类型信息在运行时是如何表示的,用来创建类的所有常规对象的
  2. 功能:Java中用Class对象来执行其RTTI
  3. 特点:每一个类都有一个Class对象
  4. 原理:通过在Java虚拟机(JVM)中启动“类加载器”子系统,类加载器加载与类同名的.class文件,这一个过程就是将Class对象载入内存中
  5. Class对象的几种方法说明
    1. getName( ):获取包含包名的类名
    2. isInterface( ):判断是否为接口
    3. getInterfaces():获取Class对象包含的接口
    4. getSimpleName():仅仅获取类名
    5. getCanonicalName():获取包含包名的类名
    6. getSuperclass():获取基类Class对象
    7. newInstance():创建Class对象对应类的实例,调用默认的构造方法
  6. 获取Class对象的方式
    1. 例子一:通过Class.forName(包名+类名);
      1. 源代码:

        package typeinfo;

        //: typeinfo/SweetShop.java

        //Examination of the way the class loader works.

        import static mypackage.Print.*;

        class Candy {

             //static 子句在类第一次加载时被执行

             static {

                   print("Loading Candy");

             }

        }

        class Gum {

             static {

                   print("Loading Gum");

             }

        }

        class Cookie {

             static {

                   print("Loading Cookie");

             }

        }

        public class SweetShop {

             public static void main(String[] args) {

                   print("inside main");

                   new Candy();

                   print("After creating Candy");

                   try {

                        //Class.forName通过类名获取Class对象的引用,如果已经存在则不再加载(比如:Class.forName("typeinfo.Candy");)

                        Class.forName("typeinfo.Gum");

                   } catch (ClassNotFoundException e) {

                        print("Couldn't find Gum");

                   }

                   print("After Class.forName(\"Gum\")");

                   new Cookie();

                   print("After creating Cookie");

             }

        /*

              * Output: inside main Loading Candy After creating Candy Loading Gum After

              * Class.forName("Gum") Loading Cookie After creating Cookie

              */// :~

      2. 结果输出:

        inside main

        Loading Candy

        After creating Candy

        Loading Gum

        After Class.forName("Gum")

        Loading Cookie

        After creating Cookie

    2. 例子二:通过其它方式获取Class对象
      1. 源代码:

        //: typeinfo/toys/ToyTest.java

        // Testing class Class.

        package typeinfo.toys;

        import static mypackage.Print.*;

        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) {

            print("Class name: " + cc.getName() + //获取包含包名的类名

              " is interface? [" + cc.isInterface() + "]"); //判断是否为接口

            print("Simple name: " + cc.getSimpleName());//仅仅获取类名

            print("Canonical name : " + cc.getCanonicalName());//获取包含包名的类名

          }

          public static void main(String[] args) {

            Class c = null;

            try {

             //获取Class对象

              c = Class.forName("typeinfo.toys.FancyToy");

            } catch(ClassNotFoundException e) {

              print("Can't find FancyToy");

              System.exit(1);

            }

            printInfo(c);    

            //获取Class对象包含的接口

            for(Class face : c.getInterfaces())

              printInfo(face);

            //获取基类Class对象

            Class up = c.getSuperclass();

            Object obj = null;

            try {

              // Requires default constructor:

              //创建Class对象对应类的实例,调用默认的构造方法

              obj = up.newInstance();

            } catch(InstantiationException e) {

              print("Cannot instantiate");

              System.exit(1);

            } catch(IllegalAccessException e) {

              print("Cannot access");

              System.exit(1);

            }

            printInfo(obj.getClass());

          }

        /* Output:

        Class name: typeinfo.toys.FancyToy is interface? [false]

        Simple name: FancyToy

        Canonical name : typeinfo.toys.FancyToy

        Class name: typeinfo.toys.HasBatteries is interface? [true]

        Simple name: HasBatteries

        Canonical name : typeinfo.toys.HasBatteries

        Class name: typeinfo.toys.Waterproof is interface? [true]

        Simple name: Waterproof

        Canonical name : typeinfo.toys.Waterproof

        Class name: typeinfo.toys.Shoots is interface? [true]

        Simple name: Shoots

        Canonical name : typeinfo.toys.Shoots

        Class name: typeinfo.toys.Toy is interface? [false]

        Simple name: Toy

        Canonical name : typeinfo.toys.Toy

        *///:~

      2. 结果输出:

        Class name: typeinfo.toys.FancyToy is interface? [false]

        Simple name: FancyToy

        Canonical name : typeinfo.toys.FancyToy

        Class name: typeinfo.toys.HasBatteries is interface? [true]

        Simple name: HasBatteries

        Canonical name : typeinfo.toys.HasBatteries

        Class name: typeinfo.toys.Waterproof is interface? [true]

        Simple name: Waterproof

        Canonical name : typeinfo.toys.Waterproof

        Class name: typeinfo.toys.Shoots is interface? [true]

        Simple name: Shoots

        Canonical name : typeinfo.toys.Shoots

        Class name: typeinfo.toys.Toy is interface? [false]

        Simple name: Toy

        Canonical name : typeinfo.toys.Toy


 

》》》》》未完:易学笔记--从0开始学JAVA(个人纯手工笔记共享 免费!免费!免费!)--比直接看书快N倍的速度掌握知识点--总共19章》》》》》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

易学笔记(qq:1776565180)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值