簡體   English   中英

通用方法中instanceof的用法

[英]Usage of instanceof in a generic method

我今天開始學習泛型,但這對我來說有點奇怪:

我有一個通用方法:

  public<T> HashMap<String, T> getAllEntitySameType(T type) {

        System.out.println(type.getClass());
        HashMap<String, T> result = null;

        if(type instanceof Project)
        {
            System.out.println(type.toString());
            System.out.println("Yes, instance of Project;");
        }

        if(type instanceof String)
        {
            System.out.println(type.toString());
            System.out.println("Yes, instance of String;");
        }
        this.getProjects();
        return result;
    }

我可以輕松確定T型的類別

    Project<Double> project = new Project<Double>();
    company2.getAllEntitySameType(project);
    company2.getAllEntitySameType("TestString");

輸出將是:

class Project
Yes, instance of Project;
class java.lang.String
TestString
Yes, instance of String;

我認為在泛型中我們不能使用實例。 我的知識還不完整。 謝謝...

您可以使用instanceof來檢查對象的原始類型 ,例如Project

if (type instanceof Project)

或對某些未知類型的Project使用適當的泛型語法:

if (type instanceof Project<?>)

但你不能具體化的參數化類型類似Project<Double>instanceof ,因為類型擦除

if (type instanceof Project<Double>) //compile error

正如Peter Lawrey 指出的那樣 ,您也無法檢查類型變量:

if (type instanceof T) //compile error

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM