javax.lang.model:如何获取字段的类型?
在 java.lang.reflect
中,人们会这样做:
Field someField = ...;
Class<?> fieldType = someField.getType();
但是我该如何处理 javax.lang.model
的 VariableElement
(其中可能代表也可能不代表一个字段)?相应的返回值将是(我猜)TypeElement
。
VariableElement someField = ...;
TypeElement fieldType = someField.???;
那么,在javax.lang.model
中,如何获取由VariableElement
表示的字段的类型(或TypeElement
) ?
顺便说一句,没有一个 Stackoverflow 标签适合 javax.lang.model ;)
In java.lang.reflect
, one would do:
Field someField = ...;
Class<?> fieldType = someField.getType();
But what do I do with javax.lang.model
's VariableElement
(which may or may not represent a field)? A corresponding return value would be (I guess) TypeElement
.
VariableElement someField = ...;
TypeElement fieldType = someField.???;
So, in javax.lang.model
, how do I get the type (or TypeElement
) of a field, represented by VariableElement
?
BTW, there is not a single Stackoverflow-tag which would fit to javax.lang.model ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,我不知道,这是正确的方法。
如果有人真正理解这个 API 告诉我,那就太好了。
但是,看起来不错。
看来
Types
类必须从当前的ProcessingEnvironment
中获取,因为它的一些内部依赖于它,所以它不是一个常见的实用程序类。Well, I don't know, it that's the right way to do this.
Would be nice if someone, who actually understands this API, told me.
But well, seams to work.
It seems that the class
Types
has to be got from currentProcessingEnvironment
because some of its internals depend on it, so it's not a usual utility class.我在尝试理解新的 JDK Doclet 毛团时偶然发现了这一点。接受的答案对我不起作用,因为 Doclet 有各种无法使用的内部类。此外,这个答案更类似于“如何将 TypeMirror 转换为 TypeElement”;鉴于 java.lang.model 的缺乏,所以问题+答案,我想无论如何我都会发布这个。
这就是我所做的:
当您有一个 TypeElement t ,它是一个类/接口“种类”时,您可以执行类似的操作以从 TypeMirror 转到 TypeElement。
我希望这对某人有帮助。
I stumbled across this trying to make sense out of the new JDK Doclet hairball. The accepted answer didn't work for me because, well, Doclet has various internal classes that cannot be used. Furthermore, this answer is more akin to "how do I convert TypeMirror to TypeElement"; given the paucity of java.lang.model SO questions+answers, I thought I'd post this anyway.
Here's what I did:
When you have a TypeElement t that is a class/interface "kind" you can do something like this to go from TypeMirror to TypeElement.
I hope this helps someone.