본문 바로가기
Java

java CloneNotSupportedException 해결 방법, 발생 예시

by solbangool 2024. 5. 20.
728x90
반응형

➰CloneNotSupportedException

▶ clone() 메서드가 호출될 때 발생할 수 있는 예외

 

  • Cloneable 인터페이스를 구현하지 않은 경우
  • Cloneable 인터페이스를 구현하지 않은 클래스에서 clone() 메서드를 호출하면 CloneNotSupportedException이 발생
public class MyClass {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        try {
            MyClass clonedObj = (MyClass) obj.clone(); // CloneNotSupportedException 발생
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

 

 

  • clone() 메서드를 오버라이드하지 않은 경우
  • Cloneable 인터페이스를 구현했지만 clone() 메서드를 오버라이드하지 않은 경우에도 CloneNotSupportedException 발생
public class MyClass implements Cloneable {
    // clone() 메서드를 오버라이드하지 않음
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        try {
            MyClass clonedObj = (MyClass) obj.clone(); // CloneNotSupportedException 발생
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

clone() 메서드를 사용 시,

1️⃣클래스에서 Cloneable 인터페이스를 구현

2️⃣clone() 메서드를 오버라이드해야 함

그렇지 않으면 CloneNotSupportedException이 발생...

 

Cloneable 인터페이스를 구현한다고 해서 자동으로 복제가 가능해지는 것❌❌

Cloneable 인터페이스를 구현한 클래스는 객체의 복제를 지원⭕ 한다는 것

실제로 복제를 수행하려면 clone() 메서드를 오버라이드해야 함~!!

 

단, clone() 메서드는 Object 클래스에서 protected 접근 지정자로 선언되어 있으므로,

오버라이드할 때는 public 접근 지정자를 사용해야 함.

 

또한, clone() 메서드를 오버라이드할 때 super.clone() 호출 필요!

 

상세 개념은 이전에 정리한 내용을 참고하면 됨

https://sbangool.tistory.com/entry/Object-clone-%EC%A0%95%EC%9D%98-%ED%99%9C%EC%9A%A9

 

반응형

댓글