17 Ağustos 2022 Çarşamba

Method Signature

Checked Exception
Açıklaması şöyle. Yani throws imzanın bir parçası değil. Kalıtan sınıfta Exception 
1. kaldırılabilir veya 
2. daha özelleştirilebilir. 
3. Ancak daha genel yapılamaz.
You can definitely have more precise or no exception, but you cannot have a more general one
Örnek 
Şöyle yaparız
interface A {
  void meth() throws IOException;
}

class B implements A {
  @Override
  void meth() throws FileNotFoundException { } // compiles fine
}

class C implements A  {
  @Override
  void meth() { } // compiles fine
}

class D implements A  {
  @Override
  void meth() throws Exception { } // compile error
}
Örnek 
Metodun imzasındaki exception'ı değiştirmek için şöyle yaparız.
interface A {
  void meth() throws IOException;
}

interface B implements A {
  void meth() throws FileNotFoundException; //Change signature
}

class C implements B  {
  @Override
  void meth() throws FileNotFoundException { } //need to use FileNotFoundException
}
Örnek
Metodu imzasında exception yoksa ancak biz checked exception fırlatmak istiyorsak şöyle yaparız
public class AnyThrow {

  public static void throwUnchecked(Throwable e) {
    AnyThrow.<RuntimeException>throwAny(e);
  }

  @SuppressWarnings("unchecked")
  private static <E extends Throwable> void throwAny(Throwable e) throws E {
    throw (E)e;
  }
}
Açıklaması şöyle
The trick relies on throwUnchecked "lying" to the compiler that the type E is RuntimeException with its call to throwAny. Since throwAny is declared as throws E, the compiler thinks that particular call can just throw RuntimeException. Of course, the trick is made possible by throwAny arbitrarily declaring E and blindly casting to it, allowing the caller to decide what its argument is cast to - terrible design when coding sanely. At runtime, E is erased and has no meaning.

As you noted, doing such a thing is a huge hack and you should document its use very well.
Kullanmak için şöyle yaparız
public void getSomething(){
  AnyThrow.throwUnchecked(new IOException(...));
}


Hiç yorum yok:

Yorum Gönder