簡體   English   中英

如何從Java方法獲取返回的Objects對象類型列表?

[英]How to get a returned List of Objects object type from a Java method?

我在Class中有一個getter方法,該方法返回對象列表。 看起來像這樣:

public List <cars> getCars() {

// some code here

}

該類還包含其他一些吸氣劑。 在另一個類中,我想獲取第一個類中包含的所有getter方法,並顯示這些方法的名稱和返回的數據類型。

我能夠獲得上述方法的名稱(getCars),並且它返回了數據類型(List)。 但是,我似乎無法獲得“汽車”作為列表包含的對象的類型。 我能得到的最好的是“ ObjectType”。 有沒有一種方法可以顯示“汽車”? 我已經閱讀了有關類型擦除的信息,以及如何在字節碼中刪除泛型的內容,因為它僅用於Java編譯器。 我的問題與類型擦除有關嗎?

是否可以顯示“汽車”一詞? 當我讀到Type Erasure時,似乎有一種從列表中獲取泛型的方法,但是我看到的示例是針對String和Integer的,而不是針對對象的。

獲取java.util.List的通用類型

謝謝

您可以使用標准Java反射掌握方法的(一般)信息:

Class<?> yourClass = Class.forName("a.b.c.ClassThatHasTheMethod");
Method getCarsMethod = yourClass.getMethod("getCars");
Type returnType = getCarsMethod.getGenericReturnType();

現在,沒有一種特別優雅的方法來處理這個returnType變量(我知道)。 它可以是普通的Class ,也可以是任何子接口 (例如ParameterizedType )。 在過去,當我這樣做時,我只需要使用instanceof和cast來處理案例。 例如:

if (returnType instanceof Class<?>) {
    Class<?> returnClass = (Class<?>)returnType;
    // do something with the class
}
else if (returnType instanceof ParameterizedType) {
    // This will be the case in your example
    ParameterizedType pt = (ParameterizedType)returnType;
    Type rawType = pt.getRawType();
    Type[] genericArgs = pt.getActualTypeArguments();

    // Here `rawType` is the class "java.util.List",
    // and `genericArgs` is a one element array containing the
    // class "cars".  So overall, pt is equivalent to List<cars>
    // as you'd expect.
    // But in order to work that out, you need
    // to call something like this method recursively, to
    // convert from `Type` to `Class`...
}
else if (...) // handle WildcardType, GenericArrayType, TypeVariable for completeness

暫無
暫無

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

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