Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 获取接口实现的通用参数_Java - Fatal编程技术网

Java 获取接口实现的通用参数

Java 获取接口实现的通用参数,java,Java,我有以下接口:接口nofifer{} 我有以下实现:类MyClass实现了通知程序,通知程序{} 有什么方法可以查询: MyClass instance = new MyClass(); Class<?> clazz = instance.getClass(); // ... MyClass实例=新建MyClass(); Class clazz=instance.getClass(); // ... 要获取MyClass实现的通知程序的类型?是-您可以调用,它返回类型[]。其中包

我有以下接口:
接口nofifer{}

我有以下实现:
类MyClass实现了通知程序,通知程序{}

有什么方法可以查询:

MyClass instance = new MyClass();
Class<?> clazz = instance.getClass();
// ...
MyClass实例=新建MyClass();
Class clazz=instance.getClass();
// ...
要获取
MyClass
实现的
通知程序
的类型?

是-您可以调用,它返回
类型[]
。其中包括类型参数信息

完整示例:

import java.lang.reflect.Type;

interface Notifier<T> { }

class Foo implements Notifier<String> {
}

class Test {
   public static void main(String[] args) {
       Class<?> clazz = Foo.class;
       for (Type iface : clazz.getGenericInterfaces()) {
           System.out.println(iface);
       }
   }
}
import java.lang.reflect.Type;
接口通知程序{}
类Foo实现通知程序{
}
课堂测试{
公共静态void main(字符串[]args){
clazz类=Foo.Class;
对于(输入iface:clazz.getGenericInterfaces()){
系统输出打印LN(iface);
}
}
}
但是,无论如何,您不能在一个类上实现同一接口两次,因此您的
类MyClass实现了Notifier,Notifier不应该编译。您应该得到一个错误,例如:

error: Notifier cannot be inherited with different arguments: 
    <java.lang.String> and <java.lang.Integer>
错误:无法使用不同的参数继承通知程序:
及
发件人:

一个类不能同时是两种接口类型的子类型,这两种接口类型是同一个泛型接口的不同参数化(§9.1.2),也不能同时是泛型接口的参数化和命名该泛型接口的原始类型的子类型,否则会发生编译时错误