티스토리 뷰
■ InvocationTargetException
Java Reflection을 사용중 InvocationTargetException가 발생하는 경우가 있습니다. 이 예외를 처음 만났을 때는 정확하게 어느 위치에서 예외가 발생하였는지 알 수 없어 굉장이 당황할 수 있습니다.(사실 제가 그랬습니다...)
InvocationTargetException는 method invoke시 호출한 메소드 내에서 Exception이 발생했을때 해당 Exception을 wrapping 해주는 Exception 클래스입니다.
실제로는 invoke 된 메서드에서 발생한 Exception이지만, 마치 invoke 구문에서 발생한것처럼 보이기 때문에 InvocationTargetException 자체의 stack trace 만으로 에러를 해결하기가 어렵습니다.
따라서 e.getTargetException을 하여 호출한 메소드 내에서 발생한 Exception을 사용하여 예외를 처리해야 합니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try { | |
m.invoke(instance, argments.toArray()); | |
} catch (IllegalAccessException e) { | |
e.printStackTrace(); | |
} catch (InvocationTargetException e) { | |
e.getTargetException().printStackTrace(); //getTargetException | |
} |
■ 예외처리 팁
Exception 처리시에는 위와 같이 e.printStackTrace는 권장되지 않는 방법입니다.. 예외 발생 위치가 정확하게 드러나기 때문에 보안에 위협이 될 수 있습니다. 따라서 표준 에러스트림을 수정하거나 Exception을 로그로 출력하는 방식등을 사용하는 것을 권장하고 있습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try { | |
m.invoke(instance, argments.toArray()); | |
} catch (IllegalAccessException e) { | |
log.error("Illiegal Access Exception", e); | |
} catch (InvocationTargetException e) { | |
log.error("fail to invoke method", e); | |
} |
'프로그래밍 > java' 카테고리의 다른 글
[예제] HttpsURLConnection Ignore Cerification (3278) | 2018.04.06 |
---|---|
Java 8 - Default Method (3617) | 2017.06.08 |
Spring - 한번에 끝내는 Spring 개발환경 셋팅 (3629) | 2017.01.15 |
java - Static Import과 제네릭 메소드 (3599) | 2017.01.14 |
Maven - 실행 가능한 Jar 파일 만들기 (3516) | 2017.01.14 |
댓글