This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Hi, I'm trying to dynamically create classes. I have an interface called Algorithm in package "App.algorithms". There are algorithms in the same package implementing the interface. From a different package called "App.gui" I want to create a new object/instance of the algorithm with the name className. Here is part of the code:
I've tried setting the className to "App.algorithms.DijkstraShortestPath" and "DijkstraShortestPath" explicitly (where DijkstraShortestPath.java is a class in "App.algorithms") but it still fails on the second line. Am I missing something? Maybe I need to do something with ClassLoader? Please can you provide a bit of code. Thanks in advance. Phil
Joined: Oct 16, 2002
Hi again, The exception that the above code throws is the InstantiationException. How would I instantiate the class within the above code? Thanks again! Phil
From the javadocs for newInstance ... Throws: IllegalAccessException - if the class or its nullary constructor is not accessible. InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason. ExceptionInInitializerError - if the initialization provoked by this method fails. SecurityException - if there is no permission to create a new instance.
Nullary is a new word to me. Get thee to a nullary? Does that just mean you have to have a no-parameter constructor? By the way, you have to have a no-parameter constructor. If you must use a constructor with parameters, you have to get into reflection, and invoke it. Here's some code I have around:
See the whole project at Jim's Pages - Ooops. That zip is gone awol. I will try to remember to upload it at home tonite. [ April 08, 2003: Message edited by: Stan James ]
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
All of which means that you have to create an instance of one of the classes that implements the Algorithm interface and then cast it to the Algorithm type. You can not create an instance of an interface directly.
"JavaRanch, where the deer and the Certified play" - David O'Meara
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com