Friday 18 May 2018

How to bypass checked exception while creating object?

One of my friend got this interview question.

Interviewer given below Employee class and wants to create an instance of it in another class, by skipping the ‘throws Exception’ validation check.

Employee.java
package com.sample.model;

public class Employee {

 public Employee() throws Exception {

 }

}

Test.java
package com.sample.test;

import com.sample.model.Employee;

public class Test {

 public static void main(String args[]) throws Exception {
  Employee emp1 = new Employee();
 }
}


Since ‘Exception’ is of type checked exception, compiler will not compile the class ‘Test.java’ until, either you handle the checked exception or throw it.



How to address this problem?
'java.lang.Class' provides 'newInstance' method to create an instance of the class. By using this, we can bypass compile-time exception checking



Test.java
package com.sample.test;

import com.sample.model.Employee;

public class Test {

 public static void main(String args[]) throws Exception {
  Employee emp1 = Employee.class.newInstance();
 }
}



You may like

No comments:

Post a Comment