一.说明
1.Type[] getGenericInterfaces
以Type的形式返回本类直接实现的接口.这样就包含了泛型参数信息
2.Class[] getInterfaces
返回本类直接实现的接口.不包含泛型参数信息
二.例子
1.接口
- public interface MyInterfaceA {
- public void sayHello();
- }
- public interface MyInterfaceB{
- public String print();
- }
- public interface MyInterfaceC<A,B> {
- public A getA();
- public B getB();
- }
2.Test.java
- import java.lang.reflect.Type;
- import java.lang.reflect.ParameterizedType;
- public class Test<A,B> implements MyInterfaceC<A,B>,MyInterfaceA,MyInterfaceB{
- private A a;
- private B b;
- //MyInterfaceC
- public A getA() {
- return a;
- }
- public B getB() {
- return b;
- }
- //MyInterfaceA
- public void sayHello() {
- }
- //MyInterfaceB
- public String print() {
- return "";
- }
- public static void main(String args[]) throws Exception{
- Type[] ts = Test.class.getGenericInterfaces();
- System.out.println("======getGenericInterfaces======:");
- for (Type t:ts) {
- System.out.println(t);
- if (ParameterizedType.class.isAssignableFrom(t.getClass())) {
- System.out.print("----------->getActualTypeArguments:");
- for (Type t1:((ParameterizedType)t).getActualTypeArguments()) {
- System.out.print(t1 + ",");
- }
- System.out.println();
- }
- }
- System.out.println();
- System.out.println("======getInterfaces======:");
- for (Class c:Test.class.getInterfaces()) {
- System.out.println(c.getName());
- }
- }
- }
输出结果:
======getGenericInterfaces======:
MyInterfaceC<A, B>
----------->getActualTypeArguments:A,B,
interface MyInterfaceA
interface MyInterfaceB
======getInterfaces======:
MyInterfaceC
MyInterfaceA
MyInterfaceB