• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Dynamic Cast

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, I have to write a program that reads a certain number of classes, whose name is known at runtime and launch them as a thread. I suppose that each of these classes implements the "Runnable" interface.
If the name was known at compile time I would write:
...
MyClass1 anInstance1=new MyClass1();
Thread t1=new Thread(anInstance1);
MyClass2 anInstance2=new MyClass2();
Thread t2=new Thread(anInstance2);
...
and so on.

In my case I use the reflection methods an I write:

public static void main(String[] args){

String externClassName = new String();

if (args.length>0) {
externClassName=args[0];
}

try {

Class inputClass= Class.forName(externClassName);
Object doOrDie=inputClass.newInstance();
if(inputClass.isInstance(doOrDie)){

Thread t1= new Thread((inputClass)doOrDie); /* this cast doesn't work! */
t1.start();
}
...
...
I've seen that if "inputClass" was known at compile time the cast would work and the code compile.
Can Someone help me?

William
 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
note your code...

object anInstance1 is implicitly casted to Runnable
hence you are suppose to write like...



this will work because Threads constructor takes
Runnable ref as argument.
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Moving this to the Intermediate forum...
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic