如何在运行时确定servlet路径?

时间:2014-08-26 17:45:51

标签: java xml servlets path context.xml

我在默认包中的目录中有一些.class文件。每个文件都有一个类,此类具有@Service注释,方法具有@Operation注释。

我知道如何在运行时读取注释,但这些文件是.class文件,我不知道如何阅读它们。 否则我想在Service文件中的路径上编写每个context.xml注释,并在运行时在web.xml文件中的url-pattern中编写每个操作。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

如果将目录中的类放入类路径中,则可以通过ClassLoader API轻松访问它们:

Class<?> clazz = this.getClass().getClassLoader().loadClass(className);

现在问题是你不知道类名,你基本上想要扫描它们。所以你可以使用其中一个库。例如,Guava提供API来通过ClassPath帮助程序实用程序扫描类路径:

ClassPath classPath = ClassPath.from(this.getClass().getClassLoader());
for (ClassPath.ClassInfo classInfo : classPath.getTopLevelClasses()) {
    Class<?> clazz = classInfo.load();
    // process annotations here
}