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

Class clazz = Baz.class. What happens ?  RSS feed

 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's a piece of code that looks like this:

Does this code actually cause an instance of Baz to be created ?
Regards,
Pho
 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I went ahead and tested the code.
It seems that the constructor is never called for the Baz class. Is it ever loaded into memory then ? Surely a Baz instance is never allocated on the heap ? Some comments appreciated.
Thanks
Pho
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Pho Tek:
There's a piece of code that looks like this:

Does this code actually cause an instance of Baz to be created ?
Regards,
Pho

Nope. You would have to call something like:

Now that uses the default (no args) constructor to create the new instance. You can get an array of all the Constructors with:

and with the one of your choosing call:

where args is an array of Object[] representing the constructors arguments. For primatives (like int) you use an Object wrapper (like Integer).
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Pho Tek:
I went ahead and tested the code.
It seems that the constructor is never called for the Baz class. Is it ever loaded into memory then ? Surely a Baz instance is never allocated on the heap ? Some comments appreciated.
Thanks
Pho

All it will do is cause the ClassLoader to load the bytecode for the class. That's why you often see code like:
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!