簡體   English   中英

獲取Java類中通用字段的類型

[英]Get Type of a generic Field in Java Class

class A<Type>{

    private Type id;

}

class B extends A<String>{


}

B b = new B();
Field idField = //reflection code to get id field

如何從“ idField”中獲取idField的確切類型,即使用String代替Type?

我不確定您要達到的目標。 但是我猜測您想確定字段“ id”的具體類型。

    public class A<T>{
    public T id;
    public Class<T> idType;

    public A(){
        idType = (Class<T>)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
}

public class B extends A<String>{

}

public static void main(String[] args) throws Exception {
    B b = new B();
    System.out.println(b.idType);
}

上面的代碼片段中的最后一個sysout語句將輸出'java.lang.String'。

這是在基類中編寫泛型功能時非常常用的技術。

暫無
暫無

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

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