• 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 assignment of class to variable

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
here is a sample of wht i want to do
private static ClassName( i want to actually classname here) objectname
for eg so the shld look like "private static Transformer transform"


// let me know if its possible to have different classes say "Publisher","Subscriber" instead of "Transformer" dynamically by accpeting the same in form of variable from user.

thanks
rahul
 
Bartender
Posts: 1844
Eclipse IDE Ruby Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Its not possible to do this the way you indicate (well, it would be possible wih dynamic class generation and compilation, but that's a little bit too complex...)
Instead, you can define the objcet to be of type "Object" (or, more likely, some known superclass or interface), and then use Class.forName(<some name> .newInstance();

Since you need to know the methods at compile time, you have to know the class (or superclass/interface) at compile time, but the actual class can be determined at runtime as shown above.
Just be sure to handle ClassNotFound or ClassCast exceptions.
 
reply
    Bookmark Topic Watch Topic
  • New Topic