簡體   English   中英

思考無法獲得階級類型

[英]Reflections could not get class type

因此,我使用Java Reflections API在另一個jar中搜索使用以下代碼擴展Foo類:

Reflections reflections = new Reflections("com.example");
for(Class<? extends Foo> e : reflections.getSubTypesOf(Foo.class)) {
    doSomething()
}

當我這樣做時,思考會拋出以下錯誤:

org.reflections.ReflectionsException: could not get type for name com.example.ExtendsFoo

有誰知道如何解決這個問題我難倒?

提前致謝!

問題可能是由於沒有可以解析名稱的類加載器(即使它可以解析子類型)。 這聽起來很矛盾,但是當我構建一個Configuration並在應用程序實例化的URLClassloader上使用ClasspathHelper.forClassLoader來弄清楚要在類路徑上掃描什么,但是沒有將所述URLClassLoader傳入Reflection配置時,我得到了錯誤消息可以正確地實例化事物。

所以你可能想嘗試以下幾點:

URLClassLoader urlcl = new URLClassLoader(urls);
Reflections reflections = new Reflections(
  new ConfigurationBuilder().setUrls(
    ClasspathHelper.forClassLoader(urlcl)
  ).addClassLoader(urlcl)
);

其中urls是包含要加載的類的jar的urls的數組。 如果我沒有對ConfigurationBuilder進行最終的addClassLoader(...)調用,我會得到與您相同的錯誤。

如果這不起作用或不適用,可能只需在ReflectionsUtil.forName(String typeName, ClassLoader... classLoaders))設置斷點即可查看發生了什么。

請查看: https//code.google.com/p/reflections/issues/detail?id = 163

反射(在其當前版本0.9.9-RC1中)不會正確地重新拋出異常。 這就是為什么你可能會錯過問題的真正原因。 在我的情況下,它是一個損壞的.class文件,我的默認類加載器無法加載並拋出異常。 所以,首先,嘗試確保您的類是真正可加載的。

使用純Java掃描類並不容易。

spring框架提供了一個名為ClassPathScanningCandidateComponentProvider的類,它可以滿足您的需求。 以下示例將在包org.example.package中找到MyClass的所有子類

ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
 provider.addIncludeFilter(new AssignableTypeFilter(MyClass.class));

// scan in org.example.package
 Set<BeanDefinition> components = provider.findCandidateComponents("org/example/package");
for (BeanDefinition component : components)
{

此方法的另一個好處是使用字節碼分析器來查找候選項,這意味着它不會加載它掃描的所有類。 class cls = Class.forName(component.getBeanClassName()); //使用class cls found}

更多信息閱讀鏈接

暫無
暫無

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

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