[英]Get generic type parameters from an object in Java
我的術語可能有誤,這些術語無法幫助我在 google 上搜索答案,但問題歸結為:
我有一組這樣聲明的對象:
public interface ActivationService<T extends Activator> {
T getActivator(Item item);
}
,所以集合是這樣聲明的:
Set<ActivationService>_activationServices = new HashSet<>();
我想將其轉換為地圖,以便更輕松地查找適當的“激活服務”。
Map<Class<? extends Activator>, Set<ActivationService>> _actsCache = new HashMap<>();
一旦我知道如何從類的對象中獲取這個T
參數,我就能夠做到。 我如何從對象中獲取它? TypeVariable
接口讓我感到困惑。
由於您的接口是ActivationService<T extends Activator>
您可能想要使用Set<ActivationService<? extends Activator>>
Set<ActivationService<? extends Activator>>
。
話雖如此,您應該已經看到獲取存儲在地圖/集合中的服務的實際通用類型存在問題,因為它可能是任意數量的不相關激活器。
要填充地圖,您可以執行以下兩項操作之一:
Class<T> getActivatorClass()
方法並提供適當的實現。MyActivatorService implements ActivatorService<MyActivator>
但不適MyActivatorService<T extends MyActivator> implements ActivatorService<T>
。 (看看這里如何做我已經使用多年的方法[現在可能有更現代的方法]: https : //www.artima.com/weblogs/viewpost.jsp?thread=208860 ) 請注意,在使用此類服務時,您最終需要使用一些強制轉換,因為您所擁有的只是ActivatorService<? extends Activator>
ActivatorService<? extends Activator>
,即無法在編譯時獲得實際的泛型類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.