簡體   English   中英

反射無法獲取從泛型接口重寫的方法的實際參數類型?

[英]Reflection can't get the actual parameter type of a method that overrides from a generic-typed interface?

編輯:對不起,我在下面提供的示例無法重現該問題...我正在嘗試找到重現此問題的正確方法。 在此之前,您可能會忽略我的問題...

通常我們會像這樣獲取方法的參數類型:

Class<?> clazz = method.getParameterTypes()[0]

我以前從未三思而后行,但最近遇到一個問題,即這樣做時我總是得到class java.lang.Object 經過檢查,我發現案件可以這樣描述:

/** A parameterized interface */
public interface IService<T> {

    Result create(T obj);
}

/** An implementation */
public class CarService implements IService<Car> {

    public Result create(Car car) { ... }
}

然后,當我使用上述方法獲取參數car的類時,結果證明它是一個class java.lang.Object

Method methods = CarService.class.getMethods();
for (Method method : methods) {
    Class<?>[] types = method.getParameterTypes();
    // when the loop meets "create" here ...
}

我想我完全忘記了有關類型擦除的一些基本知識? 但是現在,如果可能的話,在這種情況下,我真的需要獲取實際的參數類型。

是的,這是令人討厭的類型擦除。 值得一看的是您在這里的字節碼中得到了什么:

class Car {}
interface IService<T> {
    void create(T obj);
}

class CarService implements IService<Car> {
    public void create(Car car) {}
}

然后:

$ javac Test.java # Contains all the above...
$ javap -c CarService

Compiled from "Test.java"
class CarService implements IService<Car> {
  CarService();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public void create(Car);
    Code:
       0: return

  public void create(java.lang.Object);
    Code:
       0: aload_0
       1: aload_1
       2: checkcast     #2                  // class Car
       5: invokevirtual #3                  // Method create:(LCar;)V
       8: return
}

使用反射時也會顯示這些內容:

public class Test {
    public static void main(String[] args) {
        Method[] methods = CarService.class.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println(method.getName());
            for (Class<?> type : method.getParameterTypes()) {
                System.out.printf("- %s%n", type.getName());
            }
        }
    }
}

輸出:

create
- Car
create
- java.lang.Object

如何使用它取決於您要實現的目標,但是希望知道字節碼中有多種方法將有所幫助...

暫無
暫無

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

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