在使用 URLClassLoader 加载的类上可靠地查找注释 [英] Reliably finding annotations on class loaded with URLClassLoader

查看:25
本文介绍了在使用 URLClassLoader 加载的类上可靠地查找注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码生成器,它使用 URLClassLoader 在指定路径上加载类,扫描它们以获取注释,然后在字段/方法上使用反射,生成 DTO.

I have a code generator that uses URLClassLoader to load classes on a specified path, scan them for annotations, and then using Reflection on the fields/methods, generate DTOs.

在测试应用中效果很好.

It works great, in the test app.

当我把它放入Maven MOJO时,我突然失去了看到类上的javax.persistence.Entity注解的能力.它加载它们,它可以看到所有字段,但实体注释不再可见.

When I put it into the Maven MOJO, I suddenly lose the ability to see the javax.persistence.Entity annotations on the classes. It loads them, it can see all the fields, but the Entity annotation is no longer visible.

我假设这与类路径问题有关 - 是吗?测试应用程序(插件本身的 main() 函数)或 MOJO 都不是扫描类所来自的项目的一部分.但一种有效,另一种无效.

I am assuming this is something to do with Classpath issues - is it? Neither the test app (a main() function in the plugin itself) or the MOJO are part of the project that the scanned classes are from. But one works and the other doesn't.

我有一些调试代码,当它检查类时,它会打印出类上的所有注释,而在非运行版本中,它几乎没有发现.

I have a little bit of debug code that prints out all of the annotations on the class when it examines them, and in the non-running version it finds literally none.

对我如何调试/解决问题有任何想法吗?

Any ideas how I debug the problem/solve it?

推荐答案

结果证明问题非常简单,虽然我不确定为什么它在一种情况下运行良好,而在另一种情况下却没有.

The problem turned out to be pretty simple, although I'm not sure why it worked fine in one case and not in another.

我的 URLClassLoader 创建没有指定父类加载器.所以,我认为它找不到任何东西.刚用完

My URLClassLoader creation didn't specify a parent classloader. So, I assume it couldn't find anything. As soon as I used

loader = new URLClassLoader(classUrls, Thread.currentThread().getContextClassLoader());

对于类加载器,它开始工作得很好.当谈到类加载器的来龙去脉时,我非常无知,所以这并不明显.特别是因为我所遵循的示例也没有指定父级.

for the classloader, it all started working just fine. I'm pretty ignorant when it comes to the ins and outs of classloaders, so this wasn't obvious. Especially since the example I was following didn't specify a parent either.

这篇关于在使用 URLClassLoader 加载的类上可靠地查找注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆