你能以编程方式获取课堂评论吗
是否可以(是否有一种巧妙的方法)使用反射来获取类注释?我可以读取 .java 文件并获取注释,但可能没有注释,因此如果我查找 /** 的第一个实例,然后查找 */ 我可能会得到一个方法注释。
请您避免使用代码解决方案,因为我想自己破解这个问题。
Is it possible (is there a neat way) to get the class comment using reflection? I could read the .java file and get the comment but it's possible there might not be one so if I look for the first instance of /** and then */ I could end up with a method comment.
Please could you avoid code solutions as I want to crack this myself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您真的想这样做,您可以编写一个(外部)应用程序来解析源文件并提取注释。然后,使用 regex,您可以只获取您感兴趣的评论(例如,关键字“class”上方的那些,或者您想要的任何内容。
但是如果您不介意我问,您为什么要这样做?如果您确实需要访问该信息,那意味着您需要将其提升为评论之外的其他内容。应用程序中某处的常量,或类/方法上的注释,以便编译器保留它并可以使用普通方法进行访问。
If you really really want to do that, you can write an (external) application that parses your source file, and extract the comments. Then, with regex, you could take only the comments you're interested in (for example, the ones just above the keyword "class", or anything you want.
But if you don't mind me asking, why would you want to do that? If you really need to access that information, that means you need to promote it to something else than comments. Like some String constants somewhere in the application, or annotations on your class/methods, so that it's retained by the compiler and can be accessed using normal methods.
除了其他人已经提到的内容之外,从源 .java 文件读取不是反射。反射对编译后的代码、.class 文件进行操作。
Except for things already mentioned by others, reading from a source .java file is not reflection. Reflection operates on compiled code, .class files.
我认为你无法通过反射获得注释,因为编译器切断了注释,所以它们不在 .class 中。
例如,只有当您告诉 Eclipse 源代码的位置时,它才会为您提供 javadoc 帮助。
I think you cannot get comments by reflection because compiler cut off comment, so they are not in .class.
By example, Eclipse gives you javadoc help only if you tell it where sources laid.
这是不可能的。注释将从您编译的代码中删除。
It's not possible. Comments are stripped from your compiled code.
据我所知,没有办法通过反射来做到这一点。我怀疑编译后注释/JavaDoc 是否会转移到实际的类文件中。实现此目的的一种方法是使用注释处理器。注释处理不使用反射,而是使用源模型/镜像的编译时等效项。它确实允许您获取程序元素的文档,例如类声明或方法。您可以将其保留在元数据文件中以供运行时使用。
As far as I'm aware of, there's no way of doing this via reflection. I doubt commentary/JavaDoc is carried over to the actual class file after compilation. One way to do this would be the use of an annotation processor. Annotation processing doesn't use reflection, but rather the compile-time equivalent of source models/mirrors. It does allow you to get the documentation of a program element, like a class declaration or method. You could carry this over in a metadata file for use at runtime.
注释不会保留在类文件中,您必须返回原始源才能获取注释。
如果在运行时需要信息,则应将其存储在注释中,这样可以在运行时访问。
The comment is not retained in the class file, you have to go back to the original source to get comments.
If there is information you need at runtime, it should be stored in an annotation(s) This can be accessible at runtime.