0

I've been wondering about the getThis() trick, and the alternative of the unsafe cast from a self-bounded type to its type parameter.

public abstract class SelfBound<T extends SelfBound<T>> { protected abstract T getThis(); public void doSomething(T instance) { ... } public final void doSomethingWithThis() { doSomething(getThis()); } public final void doSomethingWithThisUnsafe() { doSomething((T) this); } } 

Is it possible to subclass SelfBound such that doSomethingWithThisUnsafe() throws a ClassCastException? (Is it possible to do this without subclassing SelfBound?)

3
  • I don't understand the purpose of your question. Just return some nonsense value of a type that doesn't extend SelfBound but that might have. Commented Aug 1, 2015 at 4:15
  • For example, we can have Serializable val = new Serializable() {}; return (SomeSubclass) val; inside the overriden getThis(). Commented Aug 1, 2015 at 4:16
  • @SotiriosDelimanolis he wants to know if there's a way to choose T in so that doSomethingWithThisUnsafe throws a CCE Commented Aug 1, 2015 at 4:19

1 Answer 1

3

Surely it's possible to have ClassCastException with subclassing. Here's a simple example:

public abstract class SelfBound<T extends SelfBound<T>> { protected abstract T getThis(); public void doSomething(T instance) { } public final void doSomethingWithThis() { doSomething(getThis()); } public final void doSomethingWithThisUnsafe() { doSomething((T) this); } public static class A extends SelfBound<A> { @Override protected A getThis() { return this; } } public static class B extends SelfBound<A> { @Override public void doSomething(A instance) { super.doSomething(instance); } @Override protected A getThis() { return null; } } public static void main(String[] args) { new B().doSomethingWithThisUnsafe(); } } 

Output:

Exception in thread "main" java.lang.ClassCastException: SelfBound$B cannot be cast to SelfBound$A at SelfBound$B.doSomething(SelfBound.java:1) at SelfBound.doSomethingWithThisUnsafe(SelfBound.java:6) at SelfBound.main(SelfBound.java:28) 

It's not so clear what do you mean by "without subclassing SelfBound". As SelfBound is an abstract class, you cannot call its methods without subclassing it, thus you cannot have any exception when calling its methods.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.