Java Tips

Main Menu

  • Home
  • java.lang

Old Menu

  • Java Tutorials
  • Book Reviews
  • Java SE Tips
  • Java ME Tips
  • Java EE Tips
  • Other API Tips
  • Java Applications
  • Java Libraries

Java Network

Java Forums
Java Blog
 
  • Home

How to check whether a class has a no-argument constructor

The java.lang.Class<T> class can be used to instantiate Java objects without calling explicitly their class constructor. For example, we can load a class by specifying its fully qualified name (i.e. the class name preceded by the name of the package in which the class is defined), using the forName(String className) static method of Class. If the given class can be found by the class loader, this method returns a Class object corresponding to the given class, otherwise it throws a java.lang.ClassNotFoundException. To instantiate an object of the returned class, we can use the newInstance() method, which returns an object created with the default constructor, i.e. the no-argument constructor. If the class or its constructor are not accessible form the calling code, a java.lang.IllegalAccessException is thrown, and if the instantiation fails for other reasons (for example, if the class does not have a no-argument constructor), a java.lang.InstantiationException is thrown.

  • reflection
  • java.lang.ClassNotFoundException
  • java.lang.IllegalAccessException
  • java.lang.InstantiationException
  • java.util.ArrayList

Read more: How to check whether a class has a no-argument constructor

Page 2 of 2

  • 1
  • 2

 

 


Back to Top

© 2018 Java Tips