Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how to instantiate object of class whoes class is not known at compile time?  RSS feed

 
nirali mehta
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi frnds,
this is one interview question what i faced

how can u instantiate object whoes class name is not know at compile time?
means A a=new A(); is not valid ans for this..
i think it is asking for method ,but which method that i dont know
plz help me
thank you in advance
 
Mani Ram
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use newInstance() method in java.lang.Class
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can instantiate classes dynamically using reflection. Reflection also allows you to inspect classes: lookup up a class's fields and methods and access/call them for specific objects. A good portion of the API is accessible on java.lang.Class, including newInstance() as Mani pointed out.

I find it very useful for framework and infrastructure code, less so for general day-to-day use. However, it's one of the coolest features of Java in my eyes and very fun to play with.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!