19

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 ?

AurA
  • 12,135
  • 7
  • 46
  • 63
  • Try the fully qualified package name **where** the classes are found. – Buhake Sindi Jun 12 '12 at 09:07
  • This is my fully qualified name. Inside my project I created packages by the name of com.abc and com.pqr, give example of what should be the fully qualified name in this case. – AurA Jun 12 '12 at 09:10

1 Answers1

25

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.

Nick Wilson
  • 4,959
  • 29
  • 42
  • 2
    You are correct, but I want to ask if there is any other way to load package via name without Class. I mean like suppose we don't know what class is there in the package. – AurA Jun 12 '12 at 09:19
  • 1
    You should find some useful information in [this question](http://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection). The Reflections Library looks like it might do what you want. – Nick Wilson Jun 12 '12 at 09:33