2016-03-04 45 views
1

編輯:對不起,我提供下面的例子不會重現問題...我試圖找到正確的方式來重現它。在此之前,你可以不理會我的問題...反射無法獲得覆蓋泛型類型接口的方法的實際參數類型?

通常我們搶的方法的參數類型是這樣的:

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 ... 
} 

我想我完全忘記了關於類型擦除的一些非常基本的東西?但現在我真的需要得到這種情況下的實際參數類型,如果可能的話...

+0

嘗試'method.getGenericParameterTypes()'而不是'方法.getParameterTypes()' – Ferrybig

回答

2

是的,這是類型擦除令人討厭。

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 

如何使用這將取決於你想要達到的目標,但希望知道在字節碼中有多種方法將有助於...

+0

謝謝!兩個同名的方法......這使我認爲我在問題中提供的例子並不是在第一個地方重現問題。我需要一個簡單的「if」來解決這個問題。 – fwonce

相關問題