Java反射之getInterfaces()方法


今天學習Spring3框架,在理解模擬實現Spring Ioc容器的時候遇到了getInterfaces()方法。getInterfaces()方法和Java的反射機制有關。它能夠獲得這個對象所實現的接口。

例如:

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

//獲得person對象所實現的第一個接口

詳細的例子如下:

Person類:

  1. package com.deciphering.spring;  
  2.   
  3. public class Person implements eagle,whale{  
  4.     private String name = "小明";  
  5.     private int id = 10001;   
  6.     public void Speak(String name){  
  7.         System.out.println("我的名字"+name+" ""編號"+ id);  
  8.     }     
  9.     @Override  
  10.     public void fly() {  
  11.         System.out.println("I can Fly!!!");       
  12.     }  
  13.       
  14.     @Override  
  15.     public void swim() {          
  16.         System.out.println("I can swimming!!!");  
  17.     }  
  18.     public static void main(String args[]){  
  19.         Person person = new Person();  
  20.         person.Speak("小明");  
  21.         person.fly();  
  22.         person.swim();  
  23.         System.out.println("---------------");  
  24.         Class<?> string01 = person.getClass().getInterfaces()[0];  
  25.         Class<Person> string02 = (Class<Person>) person.getClass().getInterfaces()[1];  
  26.         System.out.println(string01);  
  27.         System.out.println(string02);         
  28.     }  
  29. }  

eagle接口:

  1. package com.deciphering.spring;  
  2.   
  3. public interface eagle {  
  4.     public void fly();  
  5. }  

whale接口:

  1. package com.deciphering.spring;  
  2.   
  3. public interface whale {  
  4.     public void swim();  
  5. }  

運行結果:






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM