티스토리 뷰

Constructor 클래스중에 newInstance 메소드를 호출할 때 발생하는 예외인 InstantiationException 을 알아보자. 

InstantiationException 이 왜 발생하는지는 api 에 나와있는 내용을 한번쯤은 읽어주자.

http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Constructor.html#newInstance(java.lang.Object...)


InstantiationException - if the class that declares the underlying constructor represents an abstract class.


짧게 말해서 newInstance 메소드로 객체를 생성하려는 대상이 추상클래스이면 이 에러가 난다는 이야기다. 왜? 라고 묻는 분는... 자바문법책을 한번 더 읽어보셔야 한다. 추상클래스(abstract) 혹은 인터페이스는 new 연산자를 이용하여 직접 객체를 생성할 수 없다. 추상클래스 혹은 인터페이스를 상속받아 추상메소드들을 구현해놓은 그 클래스로 객체를 생성할 수 있다.



추상클래스를 하나 만들자.

public abstract class TargetClass4 {
	
	protected String str;
	
	public TargetClass4(String str){
		this.str = str;
	}

	public abstract void display();
}



오늘은 좀 다르게..  사용자정의 예외클래스를 하나 만들자.

public class TestException extends Exception {
	
	public TestException(String msg, Throwable cause){
		super(msg, cause);
	}
	
}



마지막으로 에러를 낼 샘플코드를 만들자.

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
 
public class ConstructorSample {
	
	
    public void execute() throws TestException {
         
        Class clazz = null;
         
        try {
            clazz = Class.forName("com.reflection.target.TargetClass4");
        } catch (ClassNotFoundException e) {
        	throw new TestException("클래스명 혹은 패키지경로를 잘못 기입했습니다.", e);
        }
         
        Constructor constructor = null;
        Class[] constructorParameterTypes = {String.class};
         
        try {
            constructor = clazz.getConstructor(constructorParameterTypes);
        } catch (SecurityException e) {
            throw new TestException("이건 다음이시간에.", e);
        } catch (NoSuchMethodException e) {
        	throw new TestException("해당 파라메터로 받는 생성자가 존재하지 않습니다.", e);
        }


        Object[] constructorParameterObjects = {"123"};
        
        try {
			constructor.newInstance(constructorParameterObjects);
			System.out.println(constructor.getName()+ " 생성자로 객체생성 성공.");
		} catch (IllegalArgumentException e) {
			throw new TestException("파라미터 타입 혹은 갯수가 맞는 생성자가 없습니다.", e);
		} catch (InstantiationException e) {
			throw new TestException("해당 클래스는 추상클래스이거나 인터페이스 입니다.", e);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
         
    }
     
    public static void main(String[] args){
        try {
			new ConstructorSample().execute();
		} catch (TestException e) {
			e.printStackTrace();
		}
    }
     
}



자 실행해보면 알겠지만 InstantiationException 에러다.


com.reflection.sample.TestException: 해당 클래스는 추상클래스이거나 인터페이스 입니다.
    at com.reflection.sample.ConstructorSample.execute(ConstructorSample.java:39)
    at com.reflection.sample.ConstructorSample.main(ConstructorSample.java:50)
Caused by: java.lang.InstantiationException
    at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:30)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.reflection.sample.ConstructorSample.execute(ConstructorSample.java:34)
    ... 1 more


내가 사용자 정의한 에러메시지가 보인다. 어쨋든 추상클래스를 가지고 Constructor 클래스를 이용하여 newInstance 는 할 수 없다.






반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함