簡體   English   中英

提取參數化類型的值時,將參數化類型類型的類參數轉換為子類形式

[英]Casting Parameterized type class argument into sub-class form when extracting the value of the Parameterized Type

如何將Parameterized類型類參數轉換為其子類形式? 我已經閱讀了許多有關提取type參數值的示例和問題,這些示例和問題應該有一個接口或抽象類,您應該從中擴展

考慮下面的代碼

type = (Class<T>) ((ParameterizedType)(getClass().getGenericSuperclass())).getActualTypeArguments()[0];

使用上面的代碼,您可以將“ type”變量轉換為(Class <T>)表示的內容。 假設<T>是Person.class

下面是完整的實現,其中Person類是要傳遞給泛型超類類型參數實參的值。 當我創建泛型子類的實例並傳遞Person類型參數形參的子類時 ,它總是被轉換為Person。 type == Student.class打印false或即使我打印類型,也總是打印Person而不是Student 我怎樣才能做到這一點? 我想要的東西有可能嗎?

通用子類

public class GenericSubClass<T extends Person> extends GenericAbstractSuper<Person> {

public Class<T> type;

@SuppressWarnings("unchecked")
public GenericSubClass() {

    type = (Class<T>) ((ParameterizedType) (getClass().getGenericSuperclass())).getActualTypeArguments()[0];

    System.out.println(type.getSimpleName());
    System.out.println(type == Student.class);
} 

public static void main(String[] args) {

    GenericSubClass<Student> genStud = new GenericSubClass<Student>();
 // GenericSubClass<Employee> genEmp = new GenericSubClass<Employee>();
 // GenericSubClass<Person> genPer = new GenericSubClass<Person>();
  }
}

通用超級抽象類

public abstract class GenericAbstractSuper<T> {
}

請我真的需要一些幫助。 我找不到類似的問題。

您將要創建GenericSubClass的子類,匿名或其他方式。

GenericSubClass<Student> genStud = new GenericSubClass<Student>(){};

現在

getClass().getGenericSuperclass()

將返回GenericSubClass<Student>Type ,並且您可以提取Student

先前,

getClass().getGenericSuperclass()

返回GenericAbstractSuper<Person>因此您正在提取Person

此技巧用於類型標記中

暫無
暫無

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

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