溫馨提示×

java怎么獲取實(shí)現(xiàn)接口的泛型

小億
156
2024-01-12 13:40:25
欄目: 編程語言

在Java中,可以通過以下方式獲取實(shí)現(xiàn)接口的泛型:

  1. 使用通配符(Wildcard):在接口中聲明泛型時(shí),可以使用通配符來表示任意類型。例如,接口定義為 interface MyInterface<T>,可以使用通配符 ? 來獲取實(shí)現(xiàn)接口的泛型類型。

示例代碼:

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. 在實(shí)現(xiàn)接口時(shí)明確指定泛型類型:在實(shí)現(xiàn)接口時(shí),可以明確指定泛型的具體類型。

示例代碼:

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");
    }
}

以上兩種方法都可以用來獲取實(shí)現(xiàn)接口的泛型類型。具體使用哪種方法取決于你的需求和代碼結(jié)構(gòu)。

0