This week's book giveaway is in the Java in General forum. We're giving away four copies of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 and have ishori Sharan & Adam L Davis on-line! See this thread for details.
First off let me explain my situation: I'm making a drawing program, somewhat of a CAD program. My intention is to let the user draw a wide variety of objects, all of which have different behaviour and drawing rountines. I would like the ability to import/remove different objects during the run-time of the program. This way when a user starts the program and they need a specific object they can import it and use it. The only problem is that each object needs it's own class (all objects implement a common interface). Therefore, to utilize the object, I have to make an instance of the class. So, now, is it possible to import a class file during the run-time? Or is there some other way to solve this problem?
As long as the class you want to "import" (not the best term for what you are doing) is in the classpath, and you want to create an instance of it using the default constructor, Class.forName( "this.that.whatever" ).newInstance() will do it for you. If you need a more complex constructor, investigate the Class.getConstructor() method and head down the reflection path. hth, bear
Nick, I'm not sure if your question is really about dynamic class loading, or about efficiency, ie, not loading classes you don't use? If it's the later, you really don't have to do anything special. The JVM will only load classes that are used by your program, at the time they are needed. If you never instantiate an object from a particular class, nor use any of its static members, that class will not get loaded.
Thanks guys, I think answer to the question, which I believe was incorrectly posed, is that each object will have a file, along with it's class file, that will refer to the class file. That way the user can choose the object with it's object file, which in turn the program can read and instantiate the class with Class.forName(String_From_Object_File).