kenpino
kenpino

Reputation: 63

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

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:

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. :)

Upvotes: 2

Views: 66

Answers (2)

dognose
dognose

Reputation: 20889

You could use reflection to call the main method of the class:

Class<?> cls = Class.forName("package.path.yourClassName");
Method m = cls.getMethod("main", String[].class); //mandatory signature for main()
String[] params = null; // any params on the call?
m.invoke(null, (Object) params); 

Note: The first parameter of invoke() would be the instance on which you'd like to invoke the call. But static mehtods don't belong to instances, therefore use null.

Upvotes: 2

Aniket Thakur
Aniket Thakur

Reputation: 68915

You have the File path to your class files from traversing via SimpleFileVisitor. Store the file name and path in a Map. When user chooses lets say Clock.class get path corresponding to it and start another java process.

Simply do

Process process = Runtime.getRuntime().exec("/pathToJDK/bin/java", pathToClassFile);

You can play around with I/O and Error streams like -

InputStream inputStream= process .getErrorStream();
//print this stream

Upvotes: 1

Related Questions