Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference Class.getConstructor and Class.getDeclaredConstructor

 
D Rog
Ranch Hand
Posts: 472
Linux Objective C Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generally problem is:
I have a class with protected default constructor, like:

I want to be able to instantiate this class, however A.class.getConstructor() throws an exception no such method. Will getDeclaredConstructor help? I notice that ReadObject implementation uses getDeclaredConstructor with following changing accessability.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
getConstructor will return a Constructor reference only for a public constructor. But getDeclaredConstructor should return a Constructor reference regardless of the constructor's access level. However, to actually invoke that constructor (e.g., calling newInstance), you would need the proper access.
 
D Rog
Ranch Hand
Posts: 472
Linux Objective C Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, it was what I'd like to hear.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic