Instantiating a class from a class<?> variable
in
Programming Questions
•
2 years ago
I would like to be able to define a class<?> variable of a class that is in my Processing workspace using Class.forName(), and then instantiate an object from that class<?> variable using newInstance(). For example:
Any ideas how I can get this to work? My overall goal is to be able to get an instance of a class based on a string of it's name.
- void setup() {
- size(100,100);
- try {
- println("Start");
- Class<?> cls = Class.forName("MyExampleClass");
- println("Middle");
- Object myExampleObject = cls.newInstance();
- println("End");
- }
- catch(Exception e) {
- System.err.println("There was an error loading class");
- System.err.println(e);
- System.exit(0);
- }
- }
- void draw() {
- println("We made it!");
- }
- Start
- There was an error loading class
- java.lang.ClassNotFoundException: MyExampleClass
- Start
- Middle
- There was an error loading class
- java.lang.InstantiationException: classTest$MyExampleClass
Any ideas how I can get this to work? My overall goal is to be able to get an instance of a class based on a string of it's name.
1
