【问题标题】:Get full path of a package situated in source folder from junit从junit获取位于源文件夹中的包的完整路径
【发布时间】:2015-06-10 04:41:11
【问题描述】:

我在 junit 中使用了以下代码来获取我的包的目录。

String pkgname = "com.acn.omi.util";
String relPath = pkgname.replace('.', '/');
URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);

但此代码在 target/test-classes 文件夹中搜索包含 src/test/java 源文件夹中的类的包,因此无法找到该包位于我的源文件夹(src/main/java)中。

如何从 junit 获取位于包中的文件。

我的目的是从该文件夹加载所有类并使用反射修改它们的字段。

【问题讨论】:

    标签: java reflection junit classloader


    【解决方案1】:

    您可以尝试使用以下代码获取类位置

    String pkgname = "com.acn.omi.util";
        String relPath = pkgname.replace('.', '\\');
        String workingDirectory = System.getProperty("user.dir");
        String requiredDirectory = workingDirectory + "\\" + "src\\test\\java"
                + relPath;
        URL resource = ClassLoader.getSystemClassLoader().getResource(
                requiredDirectory);
    

    这将为您获取测试类的完整位置。

    【讨论】:

    • 想起来,你可以更好地使用 System.getProperty(“file.separator”) 而不是 "\\" 。 windows/mac中的文件分隔符不同。
    • 我试过这条线 String requiredDirectory = workingDirectory + "\\" + "src\\main\\java\\" + relPath;但我发现 url 是空的
    • 根据getResource()方法的文档
      A URL object for reading the resource, or null if the resource could not be found or the invoker doesn't have adequate privileges to get the resource.
      请检查构造的路径是否真的存在。
    • 另外,您作为 URL 的参数提供的内容是一个目录。请提供一个文件作为 getResource 方法的参数。
    • 我建议您参考以下链接,以便能够使用 URL 加载类文件。 tutorials.jenkov.com/java-reflection/…
    【解决方案2】:

    你可以试试这样写

    URL resource = User.class.getProtectionDomain().getCodeSource().getLocation()
    

    在我的案例中,“用户”类被放置在目标包中,所以我输出它的测试如下:

    file:.../target/classes/
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-15
      • 2011-07-10
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多