您的位置:首页 > 编程语言 > Java开发

Java反射之getInterfaces()方法

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

例如:

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

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

详细的例子如下:

Person类:

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接口:
package com.deciphering.spring;

public interface eagle {
public void fly();
}

whale接口:
package com.deciphering.spring;

public interface whale {
public void swim();
}

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: