java java中的Package.getPackage返回null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10993418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Package.getPackage in java returning null
提问by AurA
I have some classes A, B, C in package com.abc
我在包 com.abc 中有一些类 A、B、C
I have a Class Main in package com.pqr
我在包 com.pqr 中有一个类 Main
Now I want to create a package object of the previous pacakge (abc).
现在我想创建一个以前的pacakge(abc)的包对象。
For this I tried,
为此我试过,
Package pkg = Package.getPackage("com.abc"); // This gives me null object in pkg
But when I do,
但是当我这样做时,
Package pkg = A.class.getPackage(); // It works fine
Can anyone notify, Why Package.getPackage("package-name") is not working ?
任何人都可以通知,为什么 Package.getPackage("package-name") 不起作用?
回答by Nick Wilson
Package.getPackage will only return a non-null value if the current ClassLoader is already aware of the package. Try this:
如果当前 ClassLoader 已经知道包,Package.getPackage 只会返回一个非空值。试试这个:
Package pkg = Package.getPackage("com.abc");
System.out.println(pkg);
Class<A> a = A.class;
pkg = Package.getPackage("com.abc");
System.out.println(pkg);
The first System.out will print 'null', the second will print the package name as the ClassLoader has then loaded a class from it.
第一个 System.out 将打印 'null',第二个将打印包名称,因为 ClassLoader 然后从中加载了一个类。