今天学习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);
- }
- }
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]; Classeagle接口:string02 = (Class ) person.getClass().getInterfaces()[1]; System.out.println(string01); System.out.println(string02); }}
- package com.deciphering.spring;
- public interface eagle {
- public void fly();
- }
package com.deciphering.spring;public interface eagle { public void fly();}whale接口:
- package com.deciphering.spring;
- public interface whale {
- public void swim();
- }
package com.deciphering.spring;public interface whale { public void swim();}运行结果: