Fast and reliable way to find out if a source code file implements an interface

后端 未结 2 1213
夕颜
夕颜 2021-01-28 00:54

Given a java source code file, what is a fast and reliable way to find out if it implements a given interface?

A reliable way would be to parse the file into a syntax tr

相关标签:
2条回答
  • 2021-01-28 01:22

    What would you do?

    I would compile the source code of the class and the interface, load both using Class.forName(), and use Class.isAssignableFrom to test if the class is a subtype of the interface.

    Relatively fast, totally reliable ... assuming that the source code is compilable.

    Note that this can all be done at runtime, and if you use a throw-away instance of a properly implemented custom classloader to do the loading, you can avoid polluting your JVM with dubious classes.

    0 讨论(0)
  • 2021-01-28 01:25

    I would say that parsing a source code file is both, fast and reliable. But "fast" is such a vague notion that it really depends, I guess. I wouldn't expect too much overhead when compared to scanning the source file for occurrences of the words "implements", though -- thus if the latter is fine for you, I'd assume the former should be acceptable too?

    The javax.tools.* API would be a good entrance point to get started; however, there are also a number of (open source) source code parsers for Java out there.

    Also, here is an introductory blog post on Oracle's websites.

    0 讨论(0)
提交回复
热议问题