newInstance() methodThe newInstance() method of Class class and Constructor class is used to create a new instance of the class. The newInstance() method of Class class can invoke zero-argument constructor, whereas newInstance() method of Constructor class can invoke any number of arguments. So, Constructor class is preferred over Class class. Syntax of newInstance() method of Class classpublic T newInstance()throws InstantiationException,IllegalAccessException Here T is the generic version. You can think of it as Object class. You will learn about generics later. newInstance() Method Example-1Let's see the simple example to use newInstance() method. FileName: Test.java Output: Hello java newInstance() method Example-2We have learned in the introductory part of this topic that the newInstance() method of the Class class can only invoke the parameterless constructor. Let's understand the same with the help of an example. FileName: ReflectionExample1.java Output: /ReflectionExample1.java:15: error: unreported exception InstantiationException; must be caught or declared to be thrown ob = classDefinition.newInstance(); ^ Note: /ReflectionExample1.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. 1 error Explanation: The newInstance() method of the Class class only invokes the zero-argument constructor. However, we need to invoke the non-zero argument constructor for that, we need to use the newInstance() method of the class Constructor. The following program shows how one can use the newInstance() method of the class Constructor to avoid the exception that has come in the above example. FileName: ReflectionExample2.java Output: My JLabel in Reflection. Next TopicUnderstanding Javap Tool |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India