java getinterface_Java反射之getInterfaces()方法

今天学习Spring3框架,在理解模拟实现Spring Ioc容器的时候遇到了getInterfaces()方法。getInterfaces()方法和Java的反射机制有关。它能够获得这个对象所实现的接口。

例如:

Class> string01 = person.getClass().getInterfaces()[0];

//获得person对象所实现的第一个接口

详细的例子如下:

Person类:

packagecom.deciphering.spring;

publicclassPersonimplementseagle,whale{

privateString name ="小明";

privateintid =10001;

publicvoidSpeak(String name){

System.out.println("我的名字"+name+" "+"编号"+ id);

}

@Override

publicvoidfly() {

System.out.println("I can Fly!!!");

}

@Override

publicvoidswim() {

System.out.println("I can swimming!!!");

}

publicstaticvoidmain(String args[]){

Person person = newPerson();

person.Speak("小明");

person.fly();

person.swim();

System.out.println("---------------");

Class> string01 = person.getClass().getInterfaces()[0];

Class string02 = (Class) person.getClass().getInterfaces()[1];

System.out.println(string01);

System.out.println(string02);

}

}package com.deciphering.spring;

public class Person implements eagle,whale{

private String name = "小明";

private int id = 10001;

public void Speak(String name){

System.out.println("我的名字"+name+" "+ "编号"+ id);

}

@Override

public void fly() {

System.out.println("I can Fly!!!");

}

@Override

public void swim() {

System.out.println("I can swimming!!!");

}

public static void main(String args[]){

Person person = new Person();

person.Speak("小明");

person.fly();

person.swim();

System.out.println("---------------");

Class<?> string01 = person.getClass().getInterfaces()[0];

Class<Person> string02 = (Class<Person>) person.getClass().getInterfaces()[1];

System.out.println(string01);

System.out.println(string02);

}

}

eagle接口:

packagecom.deciphering.spring;

publicinterfaceeagle {

publicvoidfly();

}package com.deciphering.spring;

public interface eagle {

public void fly();

}

whale接口:

packagecom.deciphering.spring;

publicinterfacewhale {

publicvoidswim();

}package com.deciphering.spring;

public interface whale {

public void swim();

}

运行结果:

447f8b6713f0795b8df865499b108400.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值