Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Package.getPackage in java returning null

I have some classes A, B, C in package com.abc

I have a Class Main in package com.pqr

Now I want to create a package object of the previous 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 ?

like image 900
AurA Avatar asked Jun 12 '12 09:06

AurA


1 Answers

Package.getPackage will only return a non-null value if the current ClassLoader is already aware of the package. Try this:

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.

like image 115
Nick Wilson Avatar answered Oct 13 '22 00:10

Nick Wilson