Шах Шах - 1 year ago 78
Java Question

How to return `this` in the generic class?

For example, I have a some class:

public class Test<T> {
public T setField() {
return this;

Of course, it's an incorrect class. But can I write it some else? (to it hasn't errors).
P.S. I know that I can write an abstract method to override it in the child class. But I ask about the generic class only (in the its class body only).

Answer Source

Casting this to T makes only sense if you use a recursive type bound. Still you need to add a cast and suppress the warning:

abstract class Test<T extends Test<T>> {
     public T setField()
         return (T)this;

Define derived classes like:

public class DerivedTest extends Test<DerivedTest> { ... }

and now this works without any casts needed in the client code:

DerivedTest d = new DerivedTest().setField();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download