I have the next snippet of code:
Certificate[] a = myFavouriteKeystore.getCertificateChain();
but I need to pass it to a method with the following signature:
void setCertificateChain(X509Certificate[] chain);
Can I do the following?:
setCertificateChain((X509certificate[]) a);
IDE(eclipse) accepts it and I assume that compiler does also, but my guess is that I'll get a ClassCastException
even in the case that all the array elements are of class X509Certificate
or a subclass of it.
You will get ClassCastException
at runtime, yes.
The cast is like lying to the compiler, saying that you really know what you are doing and even if the compiler can't prove that the cast will work - you are instructing it to trust you.
The compiler listens to you (not in all cases, i.e. you can't tell it to cast a String to an Integer for example, since String
is final and can't have sub-classes), but at the same time will inject into the byte code checkcast
instructions.
Tested, and it fails with a ClassCastException
error:
package test;
public class TestClass {
public static class A { }
public static class B extends A { }
public static void main(String [] args) {
A[] a = new A[100];
for (int i = 0; i < a.length; i++) {
a[i] = new B();
}
B[] b = (B[]) a; /* Error: ClassCastException, even if all elements are of type B */
}
}
Thanks to @Eugene that so quick answered the question.
This agrees with the policy of casting generic containers. For a container derived of a super class only the cast applies if the parameter types match. E.g: Set<A>
can be casted to SortedSet<B>
only if A
and B
are the same type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With