您的位置:首页 > 其它

14章类型信息---class对象

2014-12-11 09:37 351 查看
//: typeinfo/toys/ToyTest.java

// Testing class Class.

package typeinfo.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); }

}

public class ToyTest {

static void printInfo(Class cc) {

print("Class name: " + cc.getName() +//getName方法是带包名的类名

" is interface? [" + cc.isInterface() + "]");//isInterface方法是否是接口

print("Simple name: " + cc.getSimpleName());//getSimpleName方法不带包名的简单类名

print("Canonical name : " + cc.getCanonicalName());

//getCanonicalName方法是产生全限定的类名,也就是带包名的类名,canonical英[kə'nɒnɪk(ə)l]
美[kə'nɑnɪkl]规范化,标准的;
典范的

}

public static void main(String[] args) {

Class c = null;

try {

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

} catch(ClassNotFoundException e) {

print("Can't find FancyToy");

System.exit(1);

}

printInfo(c);

for(Class face : c.getInterfaces())

printInfo(face);

Class up = c.getSuperclass();

Object obj = null;

try {

// Requires default constructor:

obj = up.newInstance();

} catch(InstantiationException e) {

print("Cannot instantiate");

System.exit(1);

} catch(IllegalAccessException e) {

print("Cannot access");

System.exit(1);

}

printInfo(obj.getClass());

}

}

//如果去掉默认的构造器的话,调用up.newInstance();就会报无法实例化的错
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐