Java如何获取由类实现的接口?
该getClass().getInterfaces()方法返回一个数组,Class该数组表示由对象实现的接口。
package org.nhooo.example.lang;
import java.util.Date;
import java.util.Calendar;
public class ClassInterfaces {
public static void main(String[] args) {
//获取Date类的实例
Date date = Calendar.getInstance().getTime();
//获取由java.util.Date类实现的所有接口,并
//打印他们的名字。
Class[] interfaces = date.getClass().getInterfaces();
for (Class iface : interfaces) {
System.out.println("Interface Name = " + iface.getName());
}
//对于原始类型,接口将为空数组。
Class c = char.class;
interfaces = c.getInterfaces();
for (Class iface : interfaces) {
System.out.println("Interface Name = " + iface.getName());
}
}
}本java.util.Date类实现了以下接口:
Interface Name = java.io.Serializable Interface Name = java.lang.Cloneable Interface Name = java.lang.Comparable