Linux 拨号vps windows公众号手机端

java怎么获取实现接口的泛型

lewis 8年前 (2017-04-10) 阅读数 6 #程序编程
文章标签 Java

在Java中,可以通过以下方式获取实现接口的泛型:

  1. 使用通配符(Wildcard):在接口中声明泛型时,可以使用通配符来表示任意类型。例如,接口定义为 interface MyInterface<T>,可以使用通配符 ? 来获取实现接口的泛型类型。

示例代码:

interface MyInterface<T> {
    void method(T t);
}

class MyClass implements MyInterface<String> {
    @Override
    public void method(String s) {
        System.out.println(s);
    }
}

public class Main {
    public static void main(String[] args) {
        MyInterface<?> obj = new MyClass();
        obj.method("Hello");
    }
}
  1. 在实现接口时明确指定泛型类型:在实现接口时,可以明确指定泛型的具体类型。

示例代码:

interface MyInterface<T> {
    void method(T t);
}

class MyClass implements MyInterface<String> {
    @Override
    public void method(String s) {
        System.out.println(s);
    }
}

public class Main {
    public static void main(String[] args) {
        MyInterface<String> obj = new MyClass();
        obj.method("Hello");
    }
}

以上两种方法都可以用来获取实现接口的泛型类型。具体使用哪种方法取决于你的需求和代码结构。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门