Check if package exists at runtime

B

Bruce Lee

Is there anyway to check if a package exists at runtime? Class is simple -

try{
Class.forName("java.class1.Class12");
}catch(Exception e){}

but can you do this for a whole package?
 
D

Damian Brunold

Bruce said:
Is there anyway to check if a package exists at runtime? Class is simple -

try{
Class.forName("java.class1.Class12");
}catch(Exception e){}

but can you do this for a whole package?

Package.getPackages() gets all packages known to the callers
ClassLoader. At least this is what the documentation says...
 
S

Stefan Schulz

You can, if the package is sealed, just check if all classes can be
retrieved by Class.forName(). Otherwise, the notion of "whole package"
makes no sense, since there may be any number of classes also living in
that package you have never heared about.
 
C

Chris Smith

Robert Klemme said:
public static boolean packageExists(String name) {
return Package.getPackage(name)!=null;
}

Note that this will return true ONLY when a class from the package has
already been loaded. It does not somehow check if anything from the
package might be available in the future. That is the JVM's definition
of whether the package exists (it doesn't exist until it's first used),
but it's probably not the definition the OP wanted.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top