• 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对象.
  • 相关阅读:
    项目团队技术个人(提拔篇)
    Android开发者掘金(2)—技术篇
    Android开发者掘金(3) 未来
    在Android应用中放置AdMob广告的详细教程
    ant build apk
    手机产品设计中的 15 大禁忌
    Android开发者掘金(1)
    项目团队技术个人(专业篇)
    #pragram预处理指令
    c++ 异常机制
  • 原文地址:https://www.cnblogs.com/wubingshenyin/p/4412599.html
Copyright © 2020-2023  润新知