zoukankan      html  css  js  c++  java
  • RTTI-CLASS

     1 package com.xt.test;
     2 
     3 interface Test1Interface {
     4 
     5 }
     6 
     7 interface Test2Interface {
     8 
     9 }
    10 
    11 class Test1 implements Test1Interface, Test2Interface {
    12     static {
    13         System.out.println("Test1--Class");
    14     }
    15 
    16     public void print() {
    17         System.out.println("print111!");
    18     }
    19 }
    20 
    21 public class ClassTest {
    22     public static void main(String[] args) {
    23         try {
    24             Class<?> c = Class.forName("com.xt.test.Test1");
    25             Test1 cc = (Test1) c.newInstance();
    26             cc.print();
    27             System.out.println("isInterface:" + c.isInterface());
    28             // 打印类加载器的路径
    29             System.out.println("ClassLoader->Path:"
    30                     + c.getClassLoader().getResource("").getPath());
    31             // 打印class文件的路径
    32             System.out.println("Class->Path:" + c.getResource("").getPath());
    33             // 含包名的类名
    34             System.out.println("CanonicalName:" + c.getCanonicalName());
    35             System.out.println("----------------------");
    36             // 实现的接口
    37             for (Class<?> cla : c.getInterfaces()) {
    38                 System.out.println("Class->Path:"
    39                         + cla.getResource("").getPath());
    40                 System.out.println("isInterface:" + cla.isInterface());
    41             }
    42             // 得到父类,打印父类的名字
    43             Class<?> spuerClass = c.getSuperclass();
    44             System.out.println("superClassName:" + spuerClass.getName());
    45             System.out.println("----------------------");
    46             // Class.cast用法
    47             Number n = new Integer(5);
    48             Class<Integer> i = Integer.class;
    49             Integer ii = i.cast(n);
    50             System.out.println(ii);
    51         } catch (ClassNotFoundException e) {
    52             // TODO Auto-generated catch block
    53             e.printStackTrace();
    54         } catch (InstantiationException e) {
    55             // TODO Auto-generated catch block
    56             e.printStackTrace();
    57         } catch (IllegalAccessException e) {
    58             // TODO Auto-generated catch block
    59             e.printStackTrace();
    60         }
    61     }
    62 }
    类字面常量XXX.class比Class.forName("")更安全,更效率,注意,使用.class来创建对Class对象的引用的时候不会自动初始化该Class对象.
  • 相关阅读:
    MYSQL常用命令集合(转载)
    Spring(七)持久层
    Spring(六)AOP切入方式
    面试题目
    11 集合
    10 常用类
    9 异常机制
    8 面向对象之抽象类+接口+内部类
    7 面向对象的三大特征
    6 面向对象之类和对象
  • 原文地址:https://www.cnblogs.com/wubingshenyin/p/4412599.html
Copyright © 2011-2022 走看看