I'd like to ask, is there a way for a java program to see if package x is loaded? I've been making mods (for minecraft), and I have realised that almost all of my programs need to use the same methods. So I want to make an API. But I need to make sure that if the API isn't loaded, the program won't work.
Asked
Active
Viewed 139 times
2
-
If an API isn't loaded and you attempt to use it, it won't work. How do you want it to act differently to the way it does now? – Peter Lawrey Apr 14 '13 at 08:59
-
Because, the mod might load before the API. – Andrew Wong Apr 14 '13 at 09:04
-
That can happen if you use a custom classloader. Again I don't see how that is different to how it behaves now. – Peter Lawrey Apr 14 '13 at 09:05
-
Well, the program instantly calls on the API, to call a command – Andrew Wong Apr 14 '13 at 09:10
-
And what do you want it to do differently? – Peter Lawrey Apr 14 '13 at 09:11
-
Don't worry, I have a resolution. Thanks anyway! – Andrew Wong Apr 14 '13 at 09:30
3 Answers
3
You can only check for whether a given class is available on the Classpath, but that might be good enough for what you need.
Use Class.forName(...)
for this.

Thorbjørn Ravn Andersen
- 73,784
- 33
- 194
- 347
-
-
-
1That's what I was saying. But if you are not sure when the API will be called the first time, then put in a method on start up with the line of Thorbjørn Ravn Andersen's post and check for an `Exception`. – GameDroids Apr 14 '13 at 09:14
-
Or you can just call the method and catch the Error produced. I don't see the point myself. – Peter Lawrey Apr 14 '13 at 09:32
-
One general reason for testing without falling is to enable/disable menu entries without invoking functionality in the library. – Thorbjørn Ravn Andersen Apr 14 '13 at 10:30
1
As it already says in this post you could check if a class of the API can be loaded. If this is the case, the packages are available. But if the API can't be loaded, the program won't work anyway, so you could simply check for Exceptions the first time you access the API.

Community
- 1
- 1

GameDroids
- 5,584
- 6
- 40
- 59
-
-
1exactly! So when your program starts, you can either check explicitly for the availability of the API, or you could put your first parts of the initialization in a try–catch block and let the program exit *gracefully* if a `ClassNotFoundException` gets thrown. – GameDroids Apr 14 '13 at 09:08
0
I'd like to ask, is there a way for a java program to see if package x is loaded?
No. There is no such thing as loading a package in Java.

user207421
- 305,947
- 44
- 307
- 483