java class知识点

本文通过一个Java示例程序展示了如何使用反射获取类的信息,包括类名、是否为接口以及实现的接口等详细信息,并演示了如何利用反射创建对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public interface HasBatteries {

}


public interface Shoots {
}

public interface Waterproof {
}

public class Toy {
Toy(){};//默认构造器,如果不带默认构造器,则不能使用newInstance();创建对象。
Toy(int i){};
}

public 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()+"canonical name  "+cc.getCanonicalName()+"");
}


public static void main(String[] args) {
// TODO Auto-generated method stub
Class c=null;
try{
c=Class.forName("com.tkij.chapter14.Class.FancyToy");

}catch(ClassNotFoundException e){
System.out.println("cannot found fancytoy");
System.exit(1);
}
printInfo(c);
for(Class face:c.getInterfaces()){
printInfo(face);
}
Class up=c.getSuperclass();
Object obj=null;
try{
obj=up.newInstance();//使用newInstance()创建的类,必须带有默认的构造器,否则会报InstantiationException异常!
}catch(InstantiationException e){
System.out.println("canot instantiate");
}catch(IllegalAccessException e){
System.out.println("cannot access");
System.exit(1);
}
printInfo(obj.getClass());
}


}/*output
class name:com.tkij.chapter14.Class.FancyToyis interface? [false]
simple name:FancyToycanonical name  com.tkij.chapter14.Class.FancyToy
class name:com.tkij.chapter14.Class.HasBatteriesis interface? [true]
simple name:HasBatteriescanonical name  com.tkij.chapter14.Class.HasBatteries
class name:com.tkij.chapter14.Class.Waterproofis interface? [true]
simple name:Waterproofcanonical name  com.tkij.chapter14.Class.Waterproof
class name:com.tkij.chapter14.Class.Shootsis interface? [true]
simple name:Shootscanonical name  com.tkij.chapter14.Class.Shoots
class name:com.tkij.chapter14.Class.Toyis interface? [false]
simple name:Toycanonical name  com.tkij.chapter14.Class.Toy
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值