利用反射获取父类,接口信息

这个例子好似来自tij-4,(太久没更新博客了,不记得了)。
这个例子主要是用来说明,运行时能获取的被实现的接口,被继承的类的信息。
在实际开发中是一个蛮常用的手段,比如在框架中要检查某个类是否实现了某一接口。

package org.iteye.bbjava.runtimeinformation;


class Toy {

/**
* It's a contructor of Toy class,it could be used contructing an object of
* Toy at runtime.
* */
public Toy() {
// TODO Auto-generated constructor stub
}

public Toy(int i) {

}
}

interface HasBatteries {

}

interface Waterproof {

}

interface Shoots {

}

class FancyToy extends Toy implements HasBatteries, Waterproof, Shoots {
FancyToy() {
super(1);
}
}

public class ToyTest {
static void printInfo(Class cc) {
System.out.println("Class name: " + cc.getName() + " is interface?["
+ cc.isInterface() + "]");
System.out.println("Simple name: " + cc.getSimpleName());
System.out.println("Canonical name: " + cc.getCanonicalName());
}

public static void main(String[] args) {
Class c = null;
try {
c = Class.forName("org.iteye.bbjava.runtimeinformation.FancyToy");

} catch (Exception e) {
System.out.println("Can'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) {
System.out.println("Can't getInstance from up object");
System.exit(1);
} catch (IllegalAccessException e) {
System.out.println("Can't access");
System.exit(1);
}
printInfo(obj.getClass());
}
}
}



console info:[quote]Class name: org.iteye.bbjava.runtimeinformation.FancyToy is interface?[false]
Simple name: FancyToy
Canonical name: org.iteye.bbjava.runtimeinformation.FancyToy
Class name: org.iteye.bbjava.runtimeinformation.HasBatteries is interface?[true]
Simple name: HasBatteries
Canonical name: org.iteye.bbjava.runtimeinformation.HasBatteries
Class name: org.iteye.bbjava.runtimeinformation.Toy is interface?[false]
Simple name: Toy
Canonical name: org.iteye.bbjava.runtimeinformation.Toy
Class name: org.iteye.bbjava.runtimeinformation.Waterproof is interface?[true]
Simple name: Waterproof
Canonical name: org.iteye.bbjava.runtimeinformation.Waterproof
Class name: org.iteye.bbjava.runtimeinformation.Toy is interface?[false]
Simple name: Toy
Canonical name: org.iteye.bbjava.runtimeinformation.Toy
Class name: org.iteye.bbjava.runtimeinformation.Shoots is interface?[true]
Simple name: Shoots
Canonical name: org.iteye.bbjava.runtimeinformation.Shoots
Class name: org.iteye.bbjava.runtimeinformation.Toy is interface?[false]
Simple name: Toy
Canonical name: org.iteye.bbjava.runtimeinformation.Toy
[/quote]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值