samedi 31 janvier 2015

Running a class with the name within in a variable at run-time in JAVA

Been searching for a while and found nothing that addresses this issue specifically. So here it goes.


I have been learning Java and over the last few weeks I have created a bunch of classes for practice purposes. It got into my head that it would be cool to create a class that allowed me to see a list of all the classes that I have created and run them by choosing the class I want.


The way I did it and how far I have gone:



  • I read into a HashMap a list of all my classes with a SimpleFileVisitor.

  • From this list the user can chose a file by entering the number associated with the class.

  • A string is returned with the class name.


Now here comes the issue.


I end up for example with a string called "Clock.class". I want to run this. How?


Let's say that I knew the class I wanted to run. I could simple use Clock.main() The issue here is that I will not know which class to run until run-time, so I am lost.


I have been toying around with the Reflection API. I am able to instantiate an object of the Clock.class but nothing happens.


Maybe I should not be using reflection at all? Maybe there is a simpler way?


This is where I am stuck, I hope someone can enlighten me. :)


(Please be merciful! I see in these forums most of the topics are right away closed for various reasons: too broad, subjective, duplicate, ... etc. I have not found another topic on the subject so if this is indeed a duplicate please be kind and provide a link. Otherwise I don't think I an be more specific than this.)






Aucun commentaire:

Enregistrer un commentaire