Topic: Java: Instantiate classes by name from a file (Page 1 of 1) |
|
---|---|
Maniac (V) Mad Scientist From: :morF |
![]() Okay, I don't even know if this is possible, I'm just hoping it is. |
Maniac (V) Mad Scientist From: :morF |
![]() Further Googlesearch has lead me to the abstract class ClassLoader. I know that I can make use of the JVM's ClassLoader to load my classes by their names (although I don't know how I can do that, yet) and it will return a Class object to me. What I don't know, yet, is if that Class object is much the same as the Object class. I doubt it is, somehow, so I don't even know if this is what I'm looking for. |
Maniac (V) Mad Scientist From: Rochester, New York, USA |
![]() Module module = (Module)Class.forName('YourClassName'); |
Paranoid (IV) Mad Scientist From: Omicron Persei 8 |
![]() the java relfection api might be useful too. |
Maniac (V) Mad Scientist From: :morF |
![]() The solution that actually appears to have worked (so far, because I haven't yet tested it completely) is a combination of the two. code: Class currClass; Modules currModule; try { currClass = Class.forName("ClassNameFromFile"); currModule = (Modules)currClass.newInstance(); } catch (ClassNotFoundException e) { System.out.println("Could not find module"); e.printStackTrace(); } catch (InstantiationException e) { System.out.println("Could not create a module instance"); e.printStackTrace(); } catch (IllegalAccessException e) { System.out.println("Could not access named module"); e.printStackTrace(); }
|
Maniac (V) Mad Scientist From: :morF |
![]() Okay, before I say such things, I should pay attention to the warnings my compiler puts out, such as 'import java.lang.reflect.* is never used'. So you don't need to import it, just use the code. |