In general, new operator is used to create objects, but if we want to decide type of object to be created at runtime, there is no way we can use new operator. In this case, we have to use newInstance() method. Consider an example:
Object created for class:A
Class.forName() method return class Class object on which we are calling newInstance() method which will return the object of that class which we are passing as command line argument.
If the passed class doesn’t exist then ClassNotFoundException will occur.
InstantionException will occur if the passed class doesn’t contain default constructor as newInstance() method internally calls the default constructor of that particular class.
IllegalAccessException will occur if we don’t have access to the definition of specified class definition.
Related Article: Reflection in Java
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Constructor newInstance() method in Java with Examples
- instanceof operator vs isInstance() method in Java
- new operator in Java
- || operator in Java
- && operator in Java with Examples
- & Operator in Java with Examples
- Java Ternary Operator with Examples
- Java Assignment Operator with Examples
- Difference between concat() and + operator in Java
- Double colon (::) operator in Java
- Java Unary Operator with Examples
- Java Ternary Operator Puzzle
- Equality (==) operator in Java with Examples
- Diamond operator for Anonymous Inner Class with Examples in Java
- Java.lang.Short toString() method in Java with Examples
- Java.util.Collections.rotate() Method in Java with Examples
- Java.util.Collections.disjoint() Method in java with Examples
- Java lang.Long.lowestOneBit() method in Java with Examples
- Java lang.Long.highestOneBit() method in Java with Examples
- Java lang.Long.numberOfLeadingZeros() method in Java with Examples