【ThinkingInJava】27、关于class对象引用的各种关于class的方法

来源:互联网 发布:讲课视频录制软件 编辑:程序博客网 时间:2024/05/22 21:01
/*** 书本:《Thinking In Java》* 功能:关于class对象引用的各种关于class的方法* 文件:ToyTest.java* 时间:2015年4月12日19:21:32* 作者:cutter_point*/package Lesson14TypeInformation.toys;import static net.mindview.util.Print.*;interface HasBatteries {}interface Waterproof {}interface Shoots {}class Toy{Toy() {}Toy(int i) {}}class FancyToy extends Toy implements HasBatteries, Waterproof, Shoots{FancyToy() { super(1); }}class A{public String aa = " wuwuwwu";public A() {System.out.println("========================");}public A(String a) { this.aa = a; }public void get(){System.out.println("=====" + aa);}}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 {c = Class.forName("Lesson14TypeInformation.toys.FancyToy");} catch (ClassNotFoundException e) {print("Cant`t find FancyToy");System.exit(1);}printInfo(c);for(Class face : c.getInterfaces()){printInfo(face);//输出这个类型的每一个接口}Class up = c.getSuperclass();//得到父类Object obj = null;try {obj = up.newInstance();} catch (InstantiationException e) {print("Cannot instantiate");System.exit(1);} catch (IllegalAccessException e) {print("Cannot access");System.exit(1);}//实例化一个对象printInfo(obj.getClass());Class b = null;A a1 = new A("a111111111111111111111");//A a2 = new A("a222222222222222222222");Object a3 = null;A a4 = null;try {b = Class.forName("Lesson14TypeInformation.toys.A");//Class th = b.getClass();a4= (A) b.newInstance();//得到类的对象,但是没有实例化//a4 = (A) a3;a4.get();} catch (Exception e) {e.printStackTrace();}}}


输出:

Class name: Lesson14TypeInformation.toys.FancyToy is interface? [false]  obj1
Simple name: FancyToy  obj1
Canonical name : Lesson14TypeInformation.toys.FancyToy  obj1
Class name: Lesson14TypeInformation.toys.HasBatteries is interface? [true]  obj1
Simple name: HasBatteries  obj1
Canonical name : Lesson14TypeInformation.toys.HasBatteries  obj1
Class name: Lesson14TypeInformation.toys.Waterproof is interface? [true]  obj1
Simple name: Waterproof  obj1
Canonical name : Lesson14TypeInformation.toys.Waterproof  obj1
Class name: Lesson14TypeInformation.toys.Shoots is interface? [true]  obj1
Simple name: Shoots  obj1
Canonical name : Lesson14TypeInformation.toys.Shoots  obj1
Class name: Lesson14TypeInformation.toys.Toy is interface? [false]  obj1
Simple name: Toy  obj1
Canonical name : Lesson14TypeInformation.toys.Toy  obj1
========================
===== wuwuwwu





0 0
原创粉丝点击