Skip to main content
gamedev.net
🔒 Locked

[java] Dynamically loadable classes?

Started by Shadow Mint Aug 8, 2002 at 8:55 PM 3 replies 250+ views
Original Post
Shadow Mint
Shadow Mint
Is there a java equivalent to DLLs? I''ve been trawling google for the last 20 minutes and I''ve found absolutely nothing on the topic. Given a path I want to be able to open that class / archive and instanciate a class from it, but be able to pick the name of the class dynamically...or something. Basically, I want to be able to write a java application that uses plugins, written in java, specified by command line options. Any suggestions? Cheers.
TangentZ
TangentZ
Look into java.lang.ClassLoader and the the java.lang.reflect
packages. Be afraid. Be very afraid.



Kami no Itte ga ore ni zettai naru!
神はサイコロを振らない!
WayfarerX
WayfarerX
java.lang.Class.forName(String className) & java.lang.ClassLoader (for dynamicly loading classes)

Using JAR-related APIs Introduced in 1.2 (How to dynamicly mount jar files)

[edited by - wayfarerx on August 9, 2002 1:01:24 AM]
"There is no reason good should not triumph at least as often as evil. The triumph of anything is a matter of organization. If there are such things as angels, I hope that they're organized along the lines of the mafia." -Kurt Vonnegut
Shadow Mint
Shadow Mint
*sighs* This is probably gonna sound stupid to you ppl who know what you''re talking about.

OK: I wrote a new class loader. yay. It loads class data from a file (and yes, I''ll have to modify that so it works from a jar archive too).

Problem: What do I do with the Class object I get back. I cant understand the JDK docs; an I sposed to somehow use the Class to create instances of type Class? Do I do something different (use the class loader to do that)? Is this Class actually AN instance of said class; in which case, how the heck to a cast it to the appropriate class type...

Cheers!
c_wraith
c_wraith
Ack. Wrote your own classloader? Why?

Unless you''re doing something really freaky, like generating (or modifying) classes on the fly using BCEL or something, you can just use the URLClassLoader. It''s a nice versatile classloader that can load from the local filesystem (file:// URL''s), jar files (jar:// URL''s), and remote filesystems (http:// URL''s).

As far as how to use the Class object... The best approach is to specify an interface that all of your plugins will implement. Then create a no-arg constructor for your class and use newInstance on the class object to get an instance of it.

Something like this (very incomplete example):


  
Class pluginClass = loader.loadClass(pluginClassName);

Plugin p = (Plugin)pluginClass.newInstance();

p.whatever();

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.