Is there a way to force a classloader to load a package even if none of its classes have been loaded?

后端 未结 3 1404
终归单人心
终归单人心 2021-01-04 02:54

Let\'s say a java codebase has a package called \"com.example\".

At runtime, we can get this Package by calling

Package p = Package.getPackage( \"com         


        
3条回答
  •  佛祖请我去吃肉
    2021-01-04 03:27

    I assume you need this because you need to inspect its annotations. Otherwise you wouldn't be interested in having a Package reference which only operations are all around accessing annotations. This leads to the assumtion that you also have a package-info.java defined there with some annotations.

    If you check java.lang.Package you'll see that the getPackageInfo just loads the package-info class as an ordinary class.

    I had the same problem and came up with this solution.

    public static Package getPackage(String packageName) throws ClassNotFoundException {
        Class.forName(packageName+".package-info"); // makes sure package info exist and that the class loader already knows about the package
        return Package.getPackage(packageName);
    }
    

提交回复
热议问题